Search code examples
javascripteventsscroll

Detect/measure scroll speed


I'm trying to think of a way to measure the velocity of a scroll event, that would produce some sort of a number which will represent the speed (distance from scroll point A to point B relative to the time it took).


I would welcome any suggestions in the form of pseudo code... I was trying to find information on this problem, online but could not find anything. very weird since it's 2014, how could it be that there is nothing on google for this...weird!


Solution

  • var checkScrollSpeed = (function(settings){
        settings = settings || {};
      
        var lastPos, newPos, timer, delta, 
            delay = settings.delay || 50; // in "ms" (higher means lower fidelity )
      
        function clear() {
          lastPos = null;
          delta = 0;
        }
      
        clear();
        
        return function(){
          newPos = window.scrollY;
          if ( lastPos != null ){ // && newPos < maxScroll 
            delta = newPos -  lastPos;
          }
          lastPos = newPos;
          clearTimeout(timer);
          timer = setTimeout(clear, delay);
          return delta;
        };
    })();
    
    // listen to "scroll" event
    window.onscroll = function(){
      console.clear()
      console.log( checkScrollSpeed() );
    };
    body{ height:300vh }

    Demo page: http://codepen.io/vsync/pen/taAGd/

    Simplified demo: http://jsbin.com/mapafadako/edit?js,console,output


    For real fun, give a real website these rules, then copy the JS and run it