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
You can check if the combined result of the window's height and scroll top is bigger than that of the body
if (window.innerHeight + window.scrollY >= document.body.scrollHeight) {}
Using defaultView and documentElement with functional code snippet embedded:
const { defaultView } = document;
const { documentElement } = document;
const handler = evt => requestAnimationFrame(() => {
const hitBottom = (() => (defaultView.innerHeight + defaultView.pageYOffset) >= documentElement.offsetHeight)();
hitBottom
? console.log('yep')
: console.log('nope')
});
document.addEventListener('scroll', handler);
<pre style="height:110vh;background-color:fuchsia">scroll down</pre>
The accepted answer did not work for me. This did:
const element = document.createElement('div');
document.body.appendChild(element);
document.addEventListener('scroll', () => {
const viewportHeight = window.innerHeight;
const distance = element.getBoundingClientRect().top;
if (Math.floor(distance) <= viewportHeight) {
console.log('yep')
} else {
console.log('nope')
}
})
window.onscroll = function(ev) {
if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
// you're at the bottom of the page
}
};
You can look into jquery's infinite scroll:
http://www.infinite-scroll.com/infinite-scroll-jquery-plugin/
Which sounds like it does what you're asking for, assuming you're willing to use the jquery library and not hoping for a strict pure JS method.
const handleScroll = () => {
if (Math.round(window.scrollY + window.innerHeight) >= Math.round(document.body.scrollHeight)) {
onScroll();
}
};
This code worked for me in Firefox and IE as well.