jQuery datatable gets broken when initialized while being hidden
-
20-12-2019 - |
Question
Well, the title is not much explicit, but I couldn't really find something simple to explain the issue here.
Using jQuery.datatable, I generate the table on click on a bootstrap panel-collapsed. The thing is that mess up the "view". A picture is worth a thousand words here:
https://docs.google.com/file/d/0ByzbHcAxmCyvbXVVNTNYUXE1Qms/edit
If I open or resize the browser console, the view kind of refresh itself and fix the thing, I guess that's just some kind of weird rendering issue. But I don't know how fix it (no, asking the user to open the console is not a solution ^^)
Anyway, do you know how "refresh" the page, any workaround?
By the way, if you find a better title & tags, feel free!
Solution
You can make responsive recalc() the columns when a collapsible panel is shown...
var $table = $('#YourTableId');
//init the table
$table.dataTable({ "responsive" : true });
//bind to boostrap panel shown event and recalc
$table.parent().closest('.panel-collapse').on('shown.bs.collapse', function () {
$table.DataTable().columns().responsive.recalc();
});
OTHER TIPS
I found a workaround to this.
The issue is that if the table is hidden when it's initialized then it won't be displayed correctly. The trick is to hide the table using JS instead of CSS, because JS is applied once the page is loaded using $(function(){});
. So if you init the table before to hide it by JS when it will be showed then it will be correctly displayed. The order matters!