Categories
JavaScript Answers

How to Watch for Mouse Wheel Events with JavaScript?

Spread the love

We can watch for mouse wheel events with JavaScript by listening to the wheel event.

For instance, we can write:

let supportOffset = window.pageYOffset !== undefined,  
  lastKnownPos = 0,  
  scrollDir,  
  currYPos;  
window.addEventListener('wheel', (e) => {  
  currYPos = supportOffset ? window.pageYOffset : document.body.scrollTop;  
  scrollDir = lastKnownPos > currYPos ? 'up' : 'down';  
  lastKnownPos = currYPos;  
  console.log(lastKnownPos, currYPos, scrollDir)  
});

to call window.addEventListener to watch for mouse wheel motions on the browser tab.

In the event handler callback, we set currYPos to window.pageYOffset or document.body.scrollTop to get the current position of the vertical scrollbar.

Then we check that against the lastKnownPos which is the previous value of currYPos .

If lastKnownPos > currYPos is true , then we’re scrolling up since the current position is smaller in pixels than lastKnownPos .

Otherwise, we’re scrolling down.

Now when we scroll up and down on a browser tab that has scrollable content, then we should see the values in the console log logged.

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 *