Home >Web Front-end >JS Tutorial >How to Detect When a User Has Reached the Bottom of a Div with Variable Content Using jQuery?

How to Detect When a User Has Reached the Bottom of a Div with Variable Content Using jQuery?

Linda Hamilton
Linda HamiltonOriginal
2024-10-30 20:00:03423browse

How to Detect When a User Has Reached the Bottom of a Div with Variable Content Using jQuery?

Detecting End of Div Scrolling with jQuery

Objective:
Determine when a user scrolls to the bottom of a specified div element.

Question:
How can I detect when a user reaches the bottom of a div with a variable amount of content and overflow set to auto?

Answer:

To detect the end of div scrolling, use the following jQuery properties/methods:

  • $().scrollTop(): Returns the amount the element has been scrolled horizontally or vertically.
  • $().innerHeight(): Returns the inner height of the element.
  • DOMElement.scrollHeight: Returns the height of the element's content.

Combine the first two properties to get the total visible height, and compare it to the scrollHeight to determine when the user has scrolled to the bottom.

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

Additional Notes:

  • The code provided uses jQuery 1.7 syntax. For older versions, use .bind() instead of .on().
  • This solution will work properly even if the content inside the div is dynamically added or removed.
  • Adjust the event handler to your preferred container and action.

The above is the detailed content of How to Detect When a User Has Reached the Bottom of a Div with Variable Content Using 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