How do I easily find the distance between a point on the page and the bottom of the browser window using JavaScript?
Solution 1
Something like this would work I think:
var topOfDiv = $('#divID').offset().top;
var bottomOfVisibleWindow = $(window).height();
$('#divID').css('max-height', bottomOfVisibleWindow - topOfDiv - 100);
Solution 2
I had a very similar problem, except in my case I had a dynamic pop-up element (a jQuery UI Multiselect widget), to which I wanted to apply a max-height so that it never went below the bottom of the page. Using offset().top on the target element wasn't enough, because that returns the x coordinate relative to the document, and not the vertical scroll-position of the page.
So if the user scrolls down the page, the offset().top won't provide an accurate description of where they are relative to the bottom of the window - you'll need to determine the scroll position of the page.
var scrollPosition = $('body').scrollTop();
var elementOffset = $('#element').offset().top;
var elementDistance = (elementOffset - scrollPosition);
var windowHeight = $(window).height();
$('#element').css({'max-height': windowHeight - elementDistance});
Solution 3
window.innerHeight
gives you the visible height of the entire window. I did something almost identical recently so I'm pretty sure that's what you need. :) Let me know, though.
EDIT: You'll still need the Y-value of the overflowed div which you can get by document.getElementById("some_div_id").offsetHeight
, seeing that .style.top
won't give you a result unless it has been specifically set to a point via CSS. .offsetHeight
should give you the correct 'top' value.
Then it's just a matter of setting the size of the table to the window height, minus the 'top' value of the div, minus whatever arbitrary wiggle room you want for other content.
Brant Bobby
Updated on June 17, 2022Comments
-
Brant Bobby almost 2 years
A view in my web app has a table which may be extremely long, so I wrapped it in a div with
overflow: auto; max-height: 400px;
so users can scroll through it while keeping the other controls on the page visible.I want to use a bit of JavaScript to dynamically adjust the
max-height
CSS property so the div stretches to the bottom of the browser window. How can I determine this value? jQuery solutions are fine.The table doesn't start at the top of the page, so I can't just set the height to 100%.
-
Teekin over 13 yearsYou're assuming his table fills the screen from top to bottom. He needs to know the window's inner height in order to calculate how much room he has left for the table.
-
Brant Bobby over 13 yearsAaagh, the offset() method...my brain completely blanked on the existence of that. Time for more coffee.