Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: do an action after user is done scrolling

I'm trying to figure out a way to do this. I have a list of boxes, each about 150px high. I am using javascript (and jquery) and want that, after a user scrolls down a page, the page will auto scroll so that the boxes line up with the rest of the page (that is to say, if the user scrolls and the y position of the page is not divisible by 150, it will scroll to that nearest point).

Now, I at the moment, I know I can activate an event using the .scroll() jquery event, and I can make it move to a certain point using .scrollTop(). But every pixel the user moves the scroll bar activates the whole function. So is there a way to delay the function from firing until the user hasn't scrolled, and if they should begin to scroll again, the function will halt?

like image 921
DavidR Avatar asked Nov 27 '10 00:11

DavidR


People also ask

How often does scroll event fire?

Limit the minimum execution interval time of ONSCROLL event The onscroll event trigger interval time is around 10~20ms when we scrolling the mouse wheel.

Which of the following JavaScript command can be used for scrolling?

The scrollTo() method scrolls the document to specified coordinates.

How does Onscroll work?

Definition and Usage. The onscroll event occurs when an element's scrollbar is being scrolled. Tip: use the CSS overflow style property to create a scrollbar for an element.


1 Answers

As you are already using jQuery, have a look at Ben Alman's doTimeout plugin which already handles the debouncing of methods (which is what you are after).

Example shamelessly stolen from his website:

$(window).scroll(function(){
   $.doTimeout( 'scroll', 250, function(){
      // do something computationally expensive
   });
});
like image 187
Felix Kling Avatar answered Sep 23 '22 15:09

Felix Kling