Categories
JavaScript Answers

How to Determine Scroll Direction without Actually Scrolling in JavaScript?

Spread the love

Sometimes, we want to determine scroll direction without actually scrolling in our JavaScript app.

In this article, we’ll look at how to determine scroll direction without actually scrolling in our JavaScript app.

Determine Scroll Direction without Actually Scrolling in JavaScript

To determine scroll direction without actually scrolling in our JavaScript app, we can listen to the wheel event to see which direction the mouse wheel is moving.

For instance, we write:

window.addEventListener('wheel', (event) => {  
  if (event.deltaY < 0) {  
    console.log('scrolling up');  
  } else if (event.deltaY > 0) {  
    console.log('scrolling down');  
  }  
});

to add the wheel event listener to window with window.addEventListener .

In the event handler callback, we check if event.deltaY is less than 0.

If it is, we know we’re scrolling up with the mouse wheel.

And if event.deltaY is bigger than 0, then we know we’re scrolling down with the mouse wheel.

Conclusion

To determine scroll direction without actually scrolling in our JavaScript app, we can listen to the wheel event to see which direction the mouse wheel is moving.

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 *