0

I'm currently listening for scrollevents in jQuery, using the following code:

$(window).on('wheel', function(e) {

   var delta = e.originalEvent.deltaY;

   if (delta > 0) //do something
   else //do something else
});

The issue I'm having is that when the user scrolls, lots of wheel events are fired.

I want each time the user scrolls to only process the first scroll event.

I.E.: I only want to process the first wheel event and then stop listening/processing them until the user stops scrolling. At this point I want to start listening again so I can handle the next scroll.

I've seen mousewheel DOMMouseScroll used rather than .on('wheel') but don't know enough about the differences to know if that could help.

Cheers, James

James
  • 615
  • 1
  • 4
  • 22
  • Those other events will have the same issue - the wheel events fire once for each increment scrolled. The scrollwheel movement is not treated as a single event, but as a series of them - similar to how a traditional scroll event is fired once per pixel moved, instead of as a single movement of X pixels. – Rory McCrossan Nov 14 '16 at 11:48
  • http://stackoverflow.com/questions/3701311/event-when-user-stops-scrolling – Mahi Nov 14 '16 at 11:50

1 Answers1

1

You can use the jQuery debounce plugin to rate limit your function. The following code will limit the callback to executing once every 250ms.

  $(window).scroll($.debounce(250, true, function(){
    console.log('Scrolling!');
  }));

It's also possible to use the Lodash or Underscore libraries as they also have a debounce function.

Dan Nagle
  • 4,384
  • 1
  • 16
  • 28