How to detect if browser window is scrolled to bottom?
Detect a scrolled-to-bottom state in JavaScript using the following formula: window.innerHeight + window.scrollY >= document.documentElement.scrollHeight
. If the result of this condition is true, you're at the bottom. The best place to implement this check is within a scroll
event handler:
This small snippet of code listens and checks if the combined total of the visible area and the scrolled length is equal to or larger than the total page height.
Cross-browser compatibility // Be aware of browser differences
When developing for a variety of browsers, it's crucial that you use window.pageYOffset
instead of window.scrollY
to cover compatibility issues:
Just keep in mind, window.scrollY
is not supported in Internet Explorer. Hence, we provide window.pageYOffset
as a fallback.
Anticipate UI variances // Don't let the toolbars trick you
Sometimes, the scrollable area's bottom may not be the actual bottom of your page due to UI elements like toolbars or sticky footers. Modify your detection logic to factor these in:
This OFFSET_TOLERANCE
ensures that our events get triggered, even when a stubborn sticky footer wants to make us believe we are not at the bottom!
Auto-scrolling considerations // No one wants to manually scroll 'forever'
When your page has a lot of dynamic content loading at the bottom, you might want to give your users' scrolling fingers a rest and auto-scroll to the new content...but only if they are already at the bottom. Here's a pattern that can ease their suffering:
Handling dynamic content and layout changes
When content is dynamically added to the page or the layout changes, make sure to recalculate the page height to maintain accurate scroll position checking:
You should be aware that font size adjustments can affect scroll height as well. The moral of the story is, catch all the changes by subscribing to the right events.
Was this article helpful?