Hiding columns via display: none breaks the layout in DataTables 2

Hiding columns via display: none breaks the layout in DataTables 2

redfellowredfellow Posts: 5Questions: 2Answers: 0

Link to test case: https://live.datatables.net/xecaxaxa/4/edit
Description of problem:

I'm transitioning from DataTables 1 to 2, and we have a ton of tables that have some columns hidden via display: none, in order for their render function to run even when the cell is not visible to the end user, basically using trickery such as setting a class on the tr node via the render function, based on data in certain cell, to affect styling of other cells.

The issue is that in DataTables 2, the other columns aren't able reclaim available space from the hidden onces.

I attempted a workaround by setting column width of said cells to 0px in columnDefs instead of hiding them, but the width isn't affecting the colgroup properly and there's no change.

What does seem to work fine is setting:

[data-dt-column="0"],
[data-dt-column="1"],
[data-dt-column="2"],
[data-dt-column="3"] {
    display: none;
}

I could do this programmatically, but I wish there was an option to have the className of the defined column to also apply to col nodes in the colgroup (maybe an setting in init?). That way, it would minimize the headaches of jumping to the new version.

Answers

  • allanallan Posts: 61,979Questions: 1Answers: 10,161 Site admin

    Use columns.visible to hide columns and rowCallback or createdRow if you need to modify classes on the tr.

    I attempted a workaround by setting column width of said cells to 0px in columnDefs instead of hiding them, but the width isn't affecting the colgroup properly and there's no change.

    Yes, you'll get overruled by the browser for that, since the content of the column can't fit into 0px width - it will expand it to the minimum that can fit the content.

    but I wish there was an option to have the className of the defined column to also apply to col nodes in the colgroup (maybe an setting in init?).

    I looked into that, but there were a massive number of complications that it threw up. I can't recall them off the top of my head, but I do remember looking into it and backing away from it!

    The best I can think of is an event listener on init to do it programmatically as you say:

    $(document).on('init.dt', function (e) {
      var api = new DataTable.Api(e.target);
      var table = api.table().node();
    
      api.columns('.hide').indexes().each(function (col) {
        $(table).find('col[data-dt-column=' + col +']').css('display', 'none');
      })
    });
    

    https://live.datatables.net/xecaxaxa/5/edit

    That said, I'd recommend moving to ``-init columns.visible` if you can. I've no idea what impact that will have on something like Responsive.

    Allan

Sign In or Register to comment.