Learn how to detect when a user scrolls down toward the bottom of a page with raw JavaScript.
Sometimes you want to trigger an event, when the user has scrolled to the bottom of a page or a specific section.
Scroll to bottom detection (works in all modern browsers, IE9 and up)
window.onscroll = function() {
if (window.innerHeight + window.pageYOffset >= document.body.offsetHeight) {
alert("At the bottom!")
}
}
Edge case solution:
If the first one doesn’t work, try using the Math.ceil()
method on window.pageYOffset
:
window.onscroll = function() {
if ((window.innerHeight + Math.ceil(window.pageYOffset)) >= document.body.offsetHeight) {
alert('At the bottom!')
}
}
The reason for using Math.ceil
is that some browsers use subpixel precision on elements. E.g. a width or height can be 500.25px.
Math.ceil
will round upwards, e.g. 1.45px becomes 2px.
There’s also an issue with some Mac computers, which offset the window height by 1px. To work around that you can subtract a few pixels from the document height:
(window.innerHeight + window.pageYOffset) >= document.body.offsetHeight - 2
Note: scrollY
is often used instead of pageYOffset
. But scrollY
doesn’t work in Internet Explorer. For modern cross-browser
compatibility, use pageYOffset
.
Here’s a CodePen showing a working example.
If you’re confused about the relationship between window.innerHeight
, window.pageYOffset
, and document.body.offsetHeight
here’s a little helper function that logs the pixel value of each when you
scroll:
window.onscroll = function() {
console.log('Window height (px):', window.innerHeight)
console.log('Currently scrolled from top (px):', window.pageYOffset)
console.log('Document height(px):', document.body.offsetHeight)
}
That should make it easier to understand how the scroll detection function works. Initially pageYOffset
confused me. It refers to the number of current pixels scrolled vertically from top.