Categories
JavaScript Answers

How to Detect if a User is Scrolling with JavaScript?

Spread the love

To detect if a user is scrolling with JavaScript, we can watch for scroll events by adding event handlers.

For instance, we can write:

let userHasScrolled = false;  
window.onscroll = (e) => {  
  userHasScrolled = true;  
}

to add the userHasScrolled variable.

Then we set the window.onscroll property to a function that runs when we scroll.

Also, we can use the addEventListener method to add the scroll event listener.

For instance, we can write:

let userHasScrolled = false;  
window.addEventListener('scroll', (e) => {  
  userHasScrolled = true;  
})

We call window.addEventListener with 'scroll' to listen to the scroll event.

The 2nd argument is the event handler that’s run when the scroll event is emitted when we scroll.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *