How To: Heuristically set scrollY to fill browser window
How To: Heuristically set scrollY to fill browser window
A common question in the forums is when using scrollY (which adds a vertical scrollbar to the table), how to set the table height so that the entire web page is sized to just fit the browser window (so that the browser doesn't display its own scrollbars, as the user doesn't need to have two sets of scrollbars to fiddle with, and also so all the available window space is utilized).
One approach is to calculate the heights of the other elements on the page, so that the table body height can be set to
(window height) - (height of other elements)
However I noticed there looks like there's a way to heuristically figure out the height, without having to calculate the height of the other elements. There may be some gotcha I'm not aware of, so I don't know if this will work in all cases, but I'll pass on the trick in case it would be useful to others.
The body height is the combined height of all the elements on the page, while the window height is what's visible. When the body height is greater than the window height, the browser displays scrollbars. To have the web page fill the available space in the window, what we want is for the body height to end up being the same as the window height.
Here's the trick: we can figure out the height of the other elements on the page by subtracting the current height of the table body from the body height:
var otherHeight = $('body').height() - $('.dataTables_scrollBody').height()
To get the body height to end up the same as the window height, we want the sum of the other element heights and the table body height to be the window height:
var tableHeight = $(window).height() - otherHeight - 1;
I subtract an extra pixel for Firefox, which otherwise displays the browser scrollbars if the body height is exactly the window height.
Now we can set the height of the table body:
$('.dataTables_scrollBody').css('height', tableHeight + 'px');
And poof, the table magically sizes so that the entire page fits exactly within the browser window :-)
Of course, you might like to also set a minimal table height, so that if the browser window is really short the table still appears, at the cost of having the browser scrollbars appear when that happens.
tableHeight = Math.max(200, tableHeight);
Replies
An update:
Sometimes I need to call draw() after resizing the table to get the header cell columns to line up properly with the body cell columns.
Sometimes the browser scrollbars do appear unless I subtract a generous margin from the table height calculation.
The latter suggests I don't yet actually understand the situation, however I haven't investigated further since I can't use scrollY anyway with the changing column visibility bug (https://datatables.net/forums/discussion/27602/error-making-column-visible-when-using-scrolly)