user12079239
user12079239

Reputation:

How to count the number of scroll events

Here I'm trying to count the number of scroll which I triggered. I can normally get the number of scrolls, but I want to take the number of times which I have scroll. Say, If i normally scroll for a single time, It contains nearly 4-7 scroll events, where I want to consider that as one. when I scroll a little or a long scroll, i want to take the count of how many times did I have scrolled!

Here's the fiddle https://jsfiddle.net/j4es8d3x/

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

    if(e.originalEvent.wheelDelta /120 > 0) {
        console.log('scrolling up !');
    }
    else{
        console.log('scrolling down !');
    }
 }); 

Upvotes: 0

Views: 1096

Answers (2)

David
David

Reputation: 16277

There is well defined pattern for this kind of scenarios. For instance, the throttle or debounce from lodash:

enter image description here

  • debounce: Grouping a sudden burst of events (like keystrokes) into a single one.
  • throttle: Guaranteeing a constant flow of executions every X milliseconds. Like checking every 200ms your scroll position to trigger a CSS animation.

Try below code:

_.debounce(yourFunction, 300); 

Upvotes: 0

Justinas
Justinas

Reputation: 43451

You need to debounce your event:

var timer;

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

     timer = setTimeout(function () {
         // Calculate scrolls here
     }, 100);
}

Upvotes: 3

Related Questions