Fixed table height on last page
Fixed table height on last page
I know this has been asked before, but I haven't found a solution that works for me for the following reasons:
a) fixed table height solutions assume a scrolling rather than pagination approach - https://datatables.net/forums/discussion/26219 - I'd need to somehow work out the exact height I'd need to avoid scrolling in every page or a gap (plus using scrollY knocked my headers out of kilter with the columns in the tbodY)
b) solutions are for older legacy versions of datatables
c) trying to add extra empty table row elements didn't work (added in data from the start of the table)
So to cut a long story short, I took an approach from here --> https://datatables.net/forums/discussion/comment/43984/#Comment_43984
and changed it to set a margin-bottom on the last row's cells if necessary that keep a stable table height -->
"fnDrawCallback" : function (oSettings) {
var total_count = oSettings.fnRecordsTotal();
var show_num = oSettings._iDisplayLength;
var tbody = $(this).children('tbody');
var tr_count = tbody.children('tr').length;
var missing = show_num - tr_count;
// Wipe out any previously manually added margin-bottom values to the tables cells. This is done so
// a) we don't get rows with previously applied big margin bottoms appearing in the middle of the table making the table too big
// b) a row with a big margin bottoms isn't picked to calculate the row height which can throw the calculation waaayyy off course
// ('' removes the manual value and padding-bottom is recalculated from applicable css styles)
tbody.find("tr td").css ("padding-bottom", '');
if (show_num < total_count && missing > 0)
// now we can safely pick up the height for a row and make an appropriate padding-bottom value for the last row's cells
// so table keeps the same height
var lastRowHeight = tbody.find('tr:last-child').height();
var lastRowCells = tbody.find('tr:last-child td');
var existingPadding = parseFloat (lastRowCells.css ("padding-bottom"));
//console.warn ("height", lastRowHeight, lastRowCells, existingPadding);
lastRowCells.css ("padding-bottom", (existingPadding + (lastRowHeight * missing))+"px");
}
}
It works on the latest chrome (v60), firefox (v54) and ie11
Also, sorry for adding this as a new discussion but all the relevant old discussions are marked 'closed' :-)
Edit: moved the "removing manual padding-bottom" bit so it always runs regardless of whether we're on the last page, otherwise you can get the row that was manually given the large padding-bottom value appearing on a full page (found this whilst filtering)
Ps. If anyone has a simpler solution, that'd be great too
Replies
Old topic but I just registered to thank you! This is exactly what I was looking for.
Had to add an opening bracket to line 14 though to make it work in my context.
I was looking for exactly this. Thanks!