Home  >  Article  >  Web Front-end  >  How to Detect When a User Scrolls to the Bottom of a Div in jQuery?

How to Detect When a User Scrolls to the Bottom of a Div in jQuery?

Barbara Streisand
Barbara StreisandOriginal
2024-10-30 02:16:29826browse

How to Detect When a User Scrolls to the Bottom of a Div in jQuery?

How to Detect When User Scrolls to Bottom of Div with jQuery

You've created a div element with dynamic content that features an "auto" overflow setting. To enhance the user experience, you want to load additional content when the user scrolls to the bottom of this div box. However, you're unsure how to detect that specific event.

The key to this detection lies in utilizing specific jQuery properties and methods:

  • $().scrollTop(): Indicates the number of pixels the element has been scrolled
  • $().innerHeight(): Represents the inner height of the element
  • DOMElement.scrollHeight: Returns the height of the element's content

To determine when the user has reached the bottom of the div, you can compare the sum of the first two properties to the third property. When these values match, the end of the div has been reached.

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

This solution utilizes the on() method, which is preferred for event handling in jQuery versions 1.7 .

Additional Notes:

  • The event listener is attached to the div with the #flux ID, which represents the element you're interested in monitoring.
  • The alert() function is used for demonstration purposes. You can include your own logic for loading additional content here.
  • A live example can be found at http://jsfiddle.net/doktormolle/w7X9N/.

The above is the detailed content of How to Detect When a User Scrolls to the Bottom of a Div in jQuery?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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