jQuery - bind event on Scroll Stop

前端 未结 4 2077
生来不讨喜
生来不讨喜 2020-12-01 03:07

If i want to bind an event on page scrolling i can use scroll();.

But how to fire when scroll() is ended up?

I would like to reprod

4条回答
  •  天涯浪人
    2020-12-01 03:41

    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/

提交回复
热议问题