I need to detect if a user is scrolled to the bottom of a page. If they are at the bottom of the page, when I add new content to the bottom, I will automatically scroll them
window.onscroll = function(ev) {
if ((window.innerHeight + Math.ceil(window.pageYOffset)) >= document.body.offsetHeight) {
alert("you're at the bottom of the page");
}
};
This Answer will fix edge cases, this is because pageYOffset
is double
while innerHeight
and offsetHeight
are long
, so when the browser gives you the info, you may be a pixel short.
For example: on bottom of the page we have
true window.innerHeight = 10.2
true window.pageYOffset = 5.4
true document.body.offsetHeight = 15.6
Our calculation then becomes: 10 + 5.4 >= 16 which is false
To fix this we can do Math.ceil
on the pageYOffset
value.
Hope that helps.