davidlee
davidlee

Reputation: 6177

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 jQuery solution.

Upvotes: 2

Views: 3097

Answers (2)

Aakash
Aakash

Reputation: 23855

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 :)

Upvotes: 2

Nick Craver
Nick Craver

Reputation: 630637

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.

Upvotes: 12

Related Questions