0

I want to get an event when a user starts scrolling. There is a way available in JQuery using scrollstart.

Is there any way we can achieve the same in vanilla JavaScript?

prabhatojha
  • 1,925
  • 17
  • 30
  • Use a timer: https://stackoverflow.com/questions/4620906/how-do-i-know-when-ive-stopped-scrolling just check if timer === null to know that scroll is starting. – Triby Jan 30 '20 at 18:29
  • I read that answer. It won't be accurate, even adjusting the timing may not give a perfect result. – prabhatojha Jan 30 '20 at 18:35
  • Why not? if timer is off, the next time the event is triggered is a new scroll start. – Triby Jan 30 '20 at 18:38
  • @Triby man try it out at your end first, then post the answer. How would you make the timer null again? using timeout? – prabhatojha Jan 30 '20 at 18:41
  • 1
    Didn't try it, that's why I'm just commenting. Please elaborate better your question, including what have you tried and you'll get better comments, even a good and reliable answer. – Triby Jan 30 '20 at 18:43
  • @Triby, thanks, that works – prabhatojha Jan 31 '20 at 03:28

1 Answers1

0

If we tweak this answer a bit, we can achieve both, scroll start and end.

var timer = null;
window.addEventListener('scroll', function() {
    if(timer === null) {
        console.log('Scroll Started');
    }
    if(timer !== null) {
        clearTimeout(timer);        
    }
    timer = setTimeout(function() {
          console.log('Scroll Stopped');
          timer = null;
    }, 150);
}, false);
prabhatojha
  • 1,925
  • 17
  • 30