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!