Home > Web Front-end > JS Tutorial > How to Detect the End of Scroll in a Scrollable Div with jQuery?

How to Detect the End of Scroll in a Scrollable Div with jQuery?

Linda Hamilton
Release: 2024-10-29 10:06:02
Original
1051 people have browsed it

How to Detect the End of Scroll in a Scrollable Div with jQuery?

Detecting End of Scroll in a Scrollable Div with jQuery

When working with dynamic content, you may encounter the need to load more content as the user scrolls to the bottom of a container element. jQuery provides a convenient way to detect this event for divs with scrolling enabled.

To determine when the user has reached the bottom of a div, you can compare the sum of the element's scrollTop and innerHeight to its scrollHeight:

<code class="javascript">if($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight) {
  // End of scroll reached
}</code>
Copy after login

Code Implementation:

<code class="javascript">jQuery(function($) {
  $('#flux').on('scroll', function() {
    if($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight) {
      alert('End of div reached');
    }
  })
});</code>
Copy after login

Explanation:

  • scrollTop returns the number of pixels the element has been scrolled vertically.
  • innerHeight retrieves the element's inner height, excluding scrollbars.
  • scrollWidth represents the total height of the element's content, including areas outside the viewport.

When the sum of the scrollTop and innerHeight equals the scrollHeight, it indicates that the user has scrolled to the very bottom of the div.

Additional Note:

In earlier versions of jQuery, bind() was used to attach event handlers. However, as per the documentation, on() is the preferred method as of jQuery 1.7.

The above is the detailed content of How to Detect the End of Scroll in a Scrollable Div with jQuery?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template