L'evento scroll
è un evento "continuo" nel senso che viene invocato diverse volte man mano che l'utente scrolla la pagina.
Ma come possiamo sapere se l'utente ha smesso di scrollare?
Quello che dobbiamo fare è creare un timeout che viene eseguito ogni volta che l'utente scrolla il documento. Il timeout aspetta per un intervallo di tempo minimo ma sufficiente per capire che lo scrolling si è arrestato.
(function( $ ) {
$(function() {
var $output = $( "#output" ),
scrolling = "<span id='scrolling'>Scrolling</span>",
stopped = "<span id='stopped'>Stopped</span>";
$( window ).scroll(function() {
$output.html( scrolling );
clearTimeout( $.data( this, "scrollCheck" ) );
$.data( this, "scrollCheck", setTimeout(function() {
$output.html( stopped );
}, 250) );
});
});
})( jQuery );
Questa soluzione è stata proposta su StackOverflow. Una possibile implementazione sarebbe quella di astrarre la routine principale in un plugin jQuery.
(function( $ ) {
$.fn.stopScroll = function( options ) {
options = $.extend({
delay: 250,
callback: function() {}
}, options);
return this.each(function() {
var $element = $( this ),
element = this;
$element.scroll(function() {
clearTimeout( $.data( element, "scrollCheck" ) );
$.data( element, "scrollCheck", setTimeout(function() {
options.callback();
}, options.delay ) );
});
});
};
})( jQuery );
Potete visionare l'esempio di seguito.
See the Pen jQuery: check if users stop scrolling by Gabriele Romanato (@gabrieleromanato) on CodePen.