开发者

Trigger function when the page stops scrolling

How can I trigger a function when the browser window stops scrolling? Either by mouse wheel, click, space bar or arrow key? Is there any event for such action? I have tried to search online but couldn't get any solution. I'm fine with a jQue开发者_运维百科ry solution.


There's no "event" but you could make your own, like this:

$(function() {
  var timer;
  $(window).scroll(function() {
    clearTimeout(timer);
    timer = setTimeout(function() {
      $(window).trigger("scrollStop");
    }, 250);
  });
});

Then you could bind to it, like this:

$(window).bind("scrollStop", function() {
  alert("No one has scrolled me in 250ms, where's the love?");
});

This creates an event, there's no "stop" for this, but you can define your own... in this case "stop" is defined as "hasn't scrolled in 250ms", you can adjust the timer to your liking, but that's the idea.

Also, if you're just doing one thing there's no need for an event, just put your code where I'm calling $(window).trigger("scrollStop") and it'll run n milliseconds after the scroll stops.


The Non-jQuery Javascript version of the chosen answer:

var elem = document.getElementById('test');

(() => {
  var onScrollStop = (evt) => {
    // you have scroll event as evt (for any additional info)
    var scrollStopEvt = new CustomEvent('scrolling-stopped', {detail: 'foobar stopped :)'});
    elem.dispatchEvent(scrollStopEvt);
  }
  var scrollStopLag = 300 // the duration to wait before onScrollStop is triggerred.
  var timerID = 0;
  const handleScroll = (evt) => {
    clearInterval(timerID);
    timerID = setTimeout(
      () => onScrollStop(evt),
      scrollStopLag
    )
  }
  elem.addEventListener('scroll', handleScroll);
})()

elem.addEventListener(
  'scrolling-stopped', 
  (evt) => console.log(evt.detail)
)
#test {
  height: 300px;
  width: 300px;
  overflow: auto;
}

#test #test-inner {
  height: 3000px;
  background: linear-gradient(lightseagreen 0%, lightyellow 40%, lightcoral 100%);
}
<h4>Scroll inside the green box below:</h4>
<div id="test">
  <div id="test-inner"></div>
</div>

Good Luck...

P.S. I am a BIG fan of jQuery :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜