I am interested in determining when a user has reached the bottom of the page in order to fire off a custom callback event, similar to “infinite scrolling” or “endless scrolling.”
My best theory on how to go about this is to first calculate the height of the body element:
var bodyHeight = $('body').outerHeight();
Next, measure the height of the window frame:
var winHeight = $(window).height();
and lastly determine the vertical scroll position:
var scrollY = $(window).scrollTop();
However, when I insert this script into the body:
<script>
console.log(bodyHeight, winHeight);
$(window).bind("scroll", function(){
console.log(winHeight + scrollY);
});
</script>
I will often see that the calculated scroll position exceeds the height of the body. I have seen something similar when using OSX with the “elastic scrolling” but this is only using the standard scrollbar ui.
Any thoughts?
I think if you just stick with $(‘body’).height(), you should be fine.
It is possible that you see the scrollTop() is off if you have position:absolute, position:fixed or floated elements. In this case, your body element doesn’t actually wrap the tallest element, so it doesn’t work.
If that is the case, you can actually use scrollHeight.
It looks like jQuery doesn’t have a scrollHeight method (or equivalent) and there are a few browser compatibility issues with it (W3C Dom Compatibility for scrollHeight), but it works in all modern browsers.
Worst case scenario, you could get all elements, loop through them to find the max height and then use that for:
If you use that approach, I HIGHLY recommend you cache the value and update it only as needed.
JSFiddle