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

How to Detect When a User Has Scrolled to the Bottom of a Div Using jQuery?

DDD
Release: 2024-10-28 20:37:31
Original
798 people have browsed it

How to Detect When a User Has Scrolled to the Bottom of a Div Using jQuery?

Detecting Scrolling to the Bottom of a Div Using jQuery

When working with variable-height content within a div with auto-overflow, determining when a user reaches the bottom of the div can be a challenge. This article provides a solution using jQuery to detect this event.

Understanding Div Dimensions

To detect when a user scrolls to the bottom of a div, it's crucial to understand the properties and methods associated with div dimensions.

  • scrollTop(): Returns the number of pixels the content has been scrolled down vertically.
  • innerHeight(): Returns the inner height of the div, excluding scrollbars and borders.
  • scrollHeight: Returns the total height of the div's content, including hidden content.

Detecting the Bottom Scroll Event

The following jQuery code can detect when the user has reached the bottom of the div:

jQuery(function($) {
    $('#flux').on('scroll', function() {
        if($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight) {
            alert('end reached');
        }
    })
});
Copy after login

Explanation of the Code

  • $(#flux): Selects the div with the ID "flux."
  • on('scroll'): Binds the scroll event to the div.
  • if($(this).scrollTop() $(this).innerHeight() >= $(this)[0].scrollHeight):

    • Checks if the sum of the current scroll position and inner height is greater than or equal to the total content height.
    • If true, this condition indicates that the user has scrolled to or beyond the bottom of the div.
  • alert('end reached'): Displays an alert message when the end of the content is reached.

The above is the detailed content of How to Detect When a User Has Scrolled to the Bottom of a Div 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!