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.