jQuery – bind event on Scroll Stop

tiny jquery way

$.fn.scrollStopped = function(callback) {
  var that = this, $this = $(that);
  $this.scroll(function(ev) {
    clearTimeout($this.data('scrollTimeout'));
    $this.data('scrollTimeout', setTimeout(callback.bind(that), 250, ev));
  });
};

After 250 ms from the last scroll event, this will invoke the “scrollStopped” callback.

http://jsfiddle.net/wtRrV/256/

lodash (even smaller)

function onScrollStopped(domElement, callback) {
  domElement.addEventListener('scroll', _.debounce(callback, 250));
}

http://jsfiddle.net/hotw1o2j/

pure js (technically the smallest)

function onScrollStopped(domElement, callback, timeout = 250) {
  domElement.addEventListener('scroll', () => {
    clearTimeout(callback.timeout);
    callback.timeout = setTimeout(callback, timeout);
  });
}

https://jsfiddle.net/kpsxdcv8/15/

strange fact

clearTimeout and clearInterval params don’t have to be defined and can even be wrong types or even omitted.

http://jsfiddle.net/2w5zLwvx/

Leave a Comment