Scrollstop event without jQuery mobile

I try to call a function when the user stops scrolling. But I do not want to use "scrollstop" in jQuery mobile, since I do not need jQuery mobile elsewhere. Is there an equivalent event in normal jQuery or JS?

+4
source share
2 answers

try it

FIDDLE DEMO

$.fn.scrollEnd = function(callback, timeout) {          
  $(this).scroll(function(){
    var $this = $(this);
    if ($this.data('scrollTimeout')) {
      clearTimeout($this.data('scrollTimeout'));
    }
    $this.data('scrollTimeout', setTimeout(callback,timeout));
  });
};

// how to call it (with a 1000ms timeout):
$(window).scrollEnd(function(){
    alert('stopped scrolling');
   // your code-----
}, 1000);

HTML

<div style="height: 200vh">
  Long div
</div>
0
source

The only answer I found was still using jquery, and for some reason did not work in my project.

So here is my version, no jQuery needed, enjoy!

Note . Here is a snippet, but since it is embedded, it will delay the event a lot

var lastTimeScrolled = null;
var theElementYouCareAbout = document;
var intervalMilliSeconds = 500; // interval goes here
theElementYouCareAbout.onscroll = function(){
  if (performance.now() - lastTimeScrolled > intervalMilliSeconds){
    var intervalScroll = setInterval(function(){
      if (performance.now() - lastTimeScrolled > intervalMilliSeconds){
        doSomething();
        clearInterval(intervalScroll);
      }
    }.bind(intervalScroll).bind(intervalMilliSeconds), 100);
  }
  lastTimeScrolled = performance.now();
}.bind(intervalMilliSeconds);

function doSomething (){
  alert('You just stopped scrolling :)');
}
<div style="height: 200vh">
  Scroll me!
</div>
Run codeHide result
0
source

All Articles