jQuery's scroll() method allows you to execute a function when an element is scrolled. However, it doesn't provide a straightforward way to detect when scrolling stops.
To determine when scrolling has ceased, we can utilize a timed event handler. Here's an example:
$(window).scroll(function() { clearTimeout($.data(this, 'scrollTimer')); $.data(this, 'scrollTimer', setTimeout(function() { // Scrolling has stopped console.log("Haven't scrolled in 250ms!"); }, 250)); });
In this code, we set a timer and reset it every time the user scrolls. If the timer expires, it indicates that scrolling has stopped.
Alternatively, we can use the extended on() function provided by the jQuery Unevent.js extension:
$(window).on('scroll', function(e) { console.log(e.type + '-event was 250ms not triggered'); }, 250);
Unevent.js allows us to specify a delay parameter for event handlers. This way, the handler only fires if the event hasn't occurred within the given interval.
The above is the detailed content of How Can I Detect When Scrolling Stops Using jQuery?. For more information, please follow other related articles on the PHP Chinese website!