Home > Web Front-end > JS Tutorial > body text

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

Linda Hamilton
Release: 2024-10-30 20:00:03
Original
416 people have browsed it

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>
Copy after login

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!

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