Explain Codes LogoExplain Codes Logo

Detecting when user scrolls to bottom of div with jQuery

javascript
scroll-detection
jquery
performance-optimization
Nikita BarsukovbyNikita Barsukov·Feb 4, 2025
TLDR

Detect scroll to a div's bottom using jQuery's scroll event: Check when scrollTop() + innerHeight() equals or surpasses scrollHeight. Here's a neat breakdown:

$('#div').on('scroll', function() { // You thought my scroll-top game was weak, huh? if($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight) { // Ha! Can't touch this scroll bar! alert('Reached rock bottom!'); } });

For smooth sailing in jQuery ocean, stick with .on() instead of .bind(). Trust me, it ain't bindged anything since 1.7!

Client-specific scroll detection

For a targeted div scroll, bind the scroll event listener to the specific div, not the window. Trust me, window can be a real chatterbox with unrelated scrolls. Don't believe me? console.log your way out.

Tricky spaces: Padding and Borders

Now let’s talk secret hideouts, no not the batcave, just your good old borders and paddings. innerHeight includes padding, but leaves borders and scrollbar out in the cold. Manually call these guys back in with parseInt for an accurate party.

Fine print on scroll detection

Looking out for precision? Remember, scrollTop() + innerHeight() could just miss scrollHeight due to rounding off errors (Hey, math has its mood swings too!). The golden rule: Always go for greater than or equals (>=) over equals (==), less heartbreak that way.

Creating an infinite scroll feature

Ever dreamed of a scroll that never ends? Meet infinite scroll. Use our bottom detection to continually load content. But watch out for the over-eager, prevent double or even triple loading with a handy flag or by debouncing the scroll event.

Keeping it uniform across browsers

While most browsers behave like charming gentlescrolls, there might be some edge cases. Keep your code crisp across the board by thorough testing. MDN Web Docs or jQuery's official docs should be your bedtime reads for compatibility notes.

Enhancing scroll performance

Scroll events can fire more often than your tweets, so throttle it for performance. The same logic applies to $(this), cache it within the event to avoid re-querying the DOM, Like saving your favorite pizza place, but for queries.