Which event to use for checking actual height
Which event to use for checking actual height
Hi, I'm trying to achieve the following.
I load all the data into the table, then I would like to set the pageLength dynamically and redraw the table.
Basically I would like to start with a big value of pageLength and decrease it until no vertical scrollbar appears in the window.
I was able to achieve it via the following code, however I'm not completely satisfied with the solution.
$(document).ready( function () {
$('#statusTable').DataTable();
} );
var statusTable = $('#statusTable').DataTable( {
drawCallback: function(settings) {
// hide pagination buttons if we have a single page
var pagination = $(this).closest('.dataTables_wrapper').find('.dataTables_paginate');
pagination.toggle(this.api().page.info().pages > 1);
},
initComplete: function () {
setTimeout(function(){
adjustPageLen();
}, 200);
}
});
// reset pagination on resize
var windowResizeTimeout = null;
$(window).resize(function() {
if (windowResizeTimeout) clearTimeout(windowResizeTimeout);
windowResizeTimeout = setTimeout(adjustPageLen, 300);
});
(function($) {
$.fn.hasScrollBar = function() {
return this.get(0).scrollHeight > this.get(0).clientHeight;
}
})(jQuery);
function adjustPageLen() {
if ($('#statusTable').is(":visible")) {
let lengths = [2, 5, 10, 25, 50, -1];
do {
$('#statusTable').DataTable().page.len(lengths.pop()).draw();
} while($('#statusModalBody').hasScrollBar() && lengths.length>0);
}
}
The problem is that I had to use the init event and trigger my logic with a setTimeout using an arbitrary value (200) to wait until the table is visible. Otherwise the table is not rendered yet and I could not check whether the scrollbar was visible or not.
I had tried to use the draw event, however it gave me the same problem (and furthermore I would end in a infinite drawing-checking loop).
I'm hoping there is a better way to do so. Any suggestions?
Replies
Nice solution. I came up with an approach in this blog pos which might be of some interest.
The table should be fully drawn and ready when
initComplete
is triggered. I don't know why there would need to be a time out. Could you create a JSFiddle or something showing the issue perhaps?Allan
Hi @allan thanks for looking into this.
I feel so stupid, I realised what was my mistake... Indeed the table was fully drawn at initComplete. I just had it hidden at that point due to a concurrent javascript call which was running.
Bottom line, I could easily remove the setTimeout call once moving the other call, so my code is much cleaner now.
Thanks again for helping and for linking me to the other plugin (which unfortunately I could not re-use since it requires fixed height rows).
MP
No worries - great to hear that you got to the bottom of the issue!
Allan