Home >Web Front-end >JS Tutorial >How Can I Detect When a User Has Finished Scrolling with jQuery?

How Can I Detect When a User Has Finished Scrolling with jQuery?

Barbara Streisand
Barbara StreisandOriginal
2024-12-07 02:05:11293browse

How Can I Detect When a User Has Finished Scrolling with jQuery?

Detect User Scroll Completion with jQuery

In this discussion, the user is seeking a way to determine when a user has stopped scrolling, as they wish to perform a specific action (add a class to elements) once scrolling has ceased.

To achieve this, the following jQuery code can be employed:

$(window).scroll(function() {
    clearTimeout($.data(this, 'scrollTimer'));
    $.data(this, 'scrollTimer', setTimeout(function() {
        // Add the desired class here
        console.log("Scrolling has stopped!");
    }, 250));
});

In this code, a timer is used to track scroll activity. If the user continues to scroll, the timer is reset. However, if scrolling stops for a period of 250 milliseconds (as defined in the setTimeout function), the timer expires and the specified action (e.g., adding the class) is executed. This ensures that the class is only added when the user has stopped scrolling.

The above is the detailed content of How Can I Detect When a User Has Finished Scrolling with 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