Javascript: perform an action after user scroll

I am trying to find a way to do this. I have a list of boxes, each about 150px tall. I use javascript (and jquery) and I want that after the user scrolls down the page, the page will automatically scroll so that the fields match the rest of the page (that is, if the user scrolls and the y position of the page is not divided by 150, it will scroll to the nearest point).

Now, for now, I know that I can .scroll() event using the .scroll() jquery event, and I can make it jump to a specific point using .scrollTop() . But every pixel that the user moves with the scroll bar activates the whole function. So is there a way to delay the function from firing until the user scrolls, and if they start to scroll again, will the function stop?

+14
javascript jquery user-interface scroll
Nov 27 2018-10-11T00:
source share
5 answers

As you are already using jQuery, check out the Ben Alman doTimeout plugin , which already processes debouncing methods (this is what you need).

An example of shamelessly stolen from his site:

 $(window).scroll(function(){ $.doTimeout( 'scroll', 250, function(){ // do something computationally expensive }); }); 
+19
Nov 27 '10 at 1:17
source share

Of course, in the event handler for the scroll event, turn off setTimeout 100 or 200 milliseconds later. Let this setTimeout function installed inside the scroll event handler do the positioning logic above. In addition, the scroll event handler will clear all timeouts set by itself. Thus, the last time the scroll event is triggered, the setTimeout function will be completed because the scroll event did not clear it.

+6
Nov 27 2018-10-11T00:
source share

The code:

 var scrollTimeout = null; var scrollendDelay = 500; // ms $(window).scroll(function() { if ( scrollTimeout === null ) { scrollbeginHandler(); } else { clearTimeout( scrollTimeout ); } scrollTimeout = setTimeout( scrollendHandler, scrollendDelay ); }); function scrollbeginHandler() { // this code executes on "scrollbegin" document.body.style.backgroundColor = "yellow"; } function scrollendHandler() { // this code executes on "scrollend" document.body.style.backgroundColor = "gray"; scrollTimeout = null; } 
+6
Nov 27 '10 at 1:13
source share

This is basically the same as Sime Vidas's answer, but less complicated:

 var scrollTimeout = null; $(window).scroll(function(){ if (scrollTimeout) clearTimeout(scrollTimeout); scrollTimeout = setTimeout(function(){yourFunctionGoesHere()},500); }); 

500 is a delay. Should be good for mouse scroll.

+6
Feb 06 '14 at 19:17
source share

This will be the scenario where vanilla JavaScript will be useful.

 var yourFunction = function(){ // do something computationally expensive } $(window).scroll(function(){ yfTime=setTimeout("yourFunction()",250); }); 
-one
Apr 23 2018-12-12T00:
source share



All Articles