jQuery: check if users stop scrolling

The scroll event is a "continuous" event in the sense that this event fires multiple times when users scroll a web document. This is due to the fact that the scrolling movement of the finger triggers this event. Yesterday I tried to examine the scroll event in the console but nothing significant showed up. The only thing that makes a difference is the amount of time elapsed between the scroll and the release of the finger from the mouse wheel (or from the mouse surface in the special case of the Apple's Magic Mouse).

Basically, we have to create a simple JavaScript timeout that invokes an action every n-milliseconds. A good time interval is 250 or 300 milliseconds. This timeout must be reset first and then created just to be sure that there will be no unnecessary queues. Our code must be executed within the .scroll() event method's scope.


(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 );

This effective solution was originally proposed on StackOverflow. One of the possible jQuery implementations is creating a plugin to wrap the whole routine:


(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 );

You can see the example below.

See the Pen jQuery: check if users stop scrolling by Gabriele Romanato (@gabrieleromanato) on CodePen.

Back to top