67

I'm using the marvellous DataTables jQuery plug-in; http://datatables.net/ Added the FixedColumns and KeyTable extras.

Now the table does resize prettily when the window size is changed. However, the containing div of the table can also be resized in width by a jQuery animation, and I haven't found a way to resize the table with it-- it just stays stagnant in its original width. Only if I change the div width in the code before pageload, the table is resized correctly.

How can I make the DataTable resize on-the-fly according to both the window width and the containing div width?

starball
  • 20,030
  • 7
  • 43
  • 238
Emphram Stavanger
  • 4,158
  • 9
  • 35
  • 63

12 Answers12

149

What is happening is that DataTables is setting the CSS width of the table when it is initialised to a calculated value - that value is in pixels, hence why it won't resize with your dragging. The reason it does this is to stop the table and the columns (the column widths are also set) jumping around in width when you change pagination.

What you can do to stop this behaviour in DataTables is set the autoWidth parameter to false.

$('#example').dataTable( {
  "autoWidth": false
} );

That will stop DataTables adding its calculated widths to the table, leaving your (presumably) width:100% alone and allowing it to resize. Adding a relative width to the columns would also help stop the columns bouncing.

One other option that is built into DataTables is to set the sScrollX option to enable scrolling, as DataTables will set the table to be 100% width of the scrolling container. But you might not want scrolling.

The prefect solution would be if I could get the CSS width of the table (assuming one is applied - i.e. 100%), but without parsing the stylesheets, I don't see a way of doing that (i.e. basically I want $().css('width') to return the value from the stylesheet, not the pixel calculated value).

Steve Chambers
  • 37,270
  • 24
  • 156
  • 208
Allan Jardine
  • 5,303
  • 5
  • 30
  • 34
  • 3
    I added the `bAutoWidth` setting to the dataTables configuration, but it seemed to have no effect. Maybe that's due to the FixedColumns breaking the table into pieces? I already have both `sScrollX` and `sScrollY` set to `100%` Anyway, I found out that using jQuery I can trigger the "resize" event on the window, thus making dataTables resize. This is very hacky, and I don't even know how cross-browser compatible it is, so a better solution than this would indeed be appreciated. – Emphram Stavanger Nov 27 '11 at 01:31
  • In fact, is there/could there be an absolute width attribute for the table? For a different feature I'd need to also animate the table width independently from the container width, so it'd be handy if such a handle were available for jQuery to animate. – Emphram Stavanger Nov 27 '11 at 01:38
  • 7
    Setting `bAutoWidth` to false fixed the problem for me. – crush Dec 18 '13 at 19:58
  • 1
    This seems to be resolved with "Flexible width" support. Just add width="100%" to the table element in html - https://datatables.net/examples/basic_init/flexible_width.html – Michael La Voie Oct 08 '17 at 23:43
44

I know this is old, but I just solved it with this:

  var update_size = function() {
    $(oTable).css({ width: $(oTable).parent().width() });
    oTable.fnAdjustColumnSizing();  
  }

  $(window).resize(function() {
    clearTimeout(window.refresh_size);
    window.refresh_size = setTimeout(function() { update_size(); }, 250);
  });

Note: This answer applies to DataTables 1.9

Stephen
  • 3,341
  • 1
  • 22
  • 21
23

This did the trick for me.

$('#dataTable').resize()
jps
  • 1,060
  • 12
  • 19
16
$(document).ready(function() {
    $('a[data-toggle="tab"]').on( 'shown.bs.tab', function (e) {
        // var target = $(e.target).attr("href"); // activated tab
        // alert (target);
        $($.fn.dataTable.tables( true ) ).css('width', '100%');
        $($.fn.dataTable.tables( true ) ).DataTable().columns.adjust().draw();
    } ); 
});

It works for me, with "autoWidth": false,

Rui Martins
  • 3,337
  • 5
  • 35
  • 40
  • 1
    I add this too in my case $(window).resize(function() { $($.fn.dataTable.tables( true ) ).css('width', '100%'); $($.fn.dataTable.tables( true ) ).DataTable().columns.adjust().draw(); }); – Mike Castro Demaria Mar 01 '18 at 19:15
10

You should try this one.

var table = $('#example').DataTable();
table.columns.adjust().draw();

Link: column adjust in datatable

Chintan Panchal
  • 311
  • 5
  • 11
8

Use "bAutoWidth": false and go through the example given below. It is working for me.

Example:

$('#tableId').dataTable({
 "bAutoWidth": false
});
Community
  • 1
  • 1
user2314493
  • 91
  • 1
  • 3
3

I had the same challenge. When I collapsed some menus I had on the left of my web app, the datatable would not resize. Adding "autoWidth": false duirng initialization worked for me.

$('#dataTable').DataTable({'autoWidth':false, ...});
2

might be late also like the other answer but I did this early this year and the solution I came up with is using css.

    $(window).bind('resize', function () {
        /*the line below was causing the page to keep loading.
        $('#tableData').dataTable().fnAdjustColumnSizing();
        Below is a workaround. The above should automatically work.*/
        $('#tableData').css('width', '100%');
    } );
mezzie
  • 1,276
  • 8
  • 14
  • 1
    Tables are already 100% width, DataTable makes them fixed width. To prevent this: `"autoWidth": false`. In your solution, DataTable will calculate the fixed width for nothing and also doing only one time: `$('#tableData').css('width', '100%');` is enough – Erdal G. Sep 05 '16 at 10:18
1

I got this to work as follows:

First ensure that in your dataTable definition your aoColumns array includes sWidth data expressed as a % not fixed pixels or ems. Then ensure you have set the bAutoWidth property to false Then add this little but of JS:

update_table_size = function(a_datatable) {
  if (a_datatable == null) return;
  var dtb;
  if (typeof a_datatable === 'string') dtb = $(a_datatable)
  else dtb = a_datatable;
  if (dtb == null) return;

  dtb.css('width', dtb.parent().width());
  dtb.fnAdjustColumSizing();
}

$(window).resize(function() {
  setTimeout(function(){update_table_size(some_table_selector_or_table_ref)}, 250);
});

Works a treat and my table cells handle the white-space: wrap; CSS (which wasn't working without setting the sWidth, and was what led me to this question.)

Dave Sag
  • 13,266
  • 14
  • 86
  • 134
  • http://konzertagentur-koerner.de/index.php/Ajax_Controller/getIndex2/book : the automatic column/window resizing is not working, do you have an idea why not? I have the AutoWidth Prop. set to false and also the width size is set relative, not absolute – Timo Dec 20 '13 at 15:05
1

I was having the exact same problem as OP. I had a DataTable which would not readjust its width after a jQuery animation (toogle("fast")) resized its container.

After reading these answers, and lots of try and error this did the trick for me:

  $("#animatedElement").toggle(100, function() {    
    $("#dataTableId").resize();
  });

After many test, i realized that i need to wait for the animation to finish for dataTables to calculate the correct width.

1

The code below is the combination of Chintan Panchal's answer along with Antoine Leclair's comment (placing the code in the windows resize event). (I didn't need the debounce mentioned by Antoine Leclair, however that could be a best practice.)

  $(window).resize( function() {
      $("#example").DataTable().columns.adjust().draw();
  });

This was the approach that worked in my case.

StackOverflowUser
  • 945
  • 12
  • 10
1

Have you tried capturing the div resize event and doing .fnDraw() on the datatable? fnDraw should resize the table for you

Keith.Abramo
  • 6,952
  • 2
  • 32
  • 46
  • I have a `setTimeout` set at 300 milliseconds (the length of the animation) to call the `.fnDraw()` function. However, it doesn't seem to have any effect. Also, I feel this is a sort of a kludge fix, because I'd like the table resizing to be a smooth animation together with the div resizing, instead of just "flicking" into proper size after the animation is over. – Emphram Stavanger Nov 26 '11 at 14:23
  • So a couple things come to mind. First code samples with questions when you have them are very valuable. They go much further than trying to describe your code. Second, you could try to listen in div resize jquery event and then adjust your datatable with accordingly. However, you will have to somehow adjust the number of rows you return per page when you resize dynamically. I'm sure you can do that by tweaking the fnSettings options. – Keith.Abramo Nov 26 '11 at 14:29