Categories
JavaScript Answers

How to listen for the mouse wheel event in modern browsers with JavaScript?

Spread the love

Sometimes, we want to listen for the mouse wheel event in modern browsers with JavaScript.

In this article, we’ll look at how to listen for the mouse wheel event in modern browsers with JavaScript.

How to listen for the mouse wheel event in modern browsers with JavaScript?

To listen for the mouse wheel event in modern browsers with JavaScript, we listen to the wheel event.

For instance, we write

window.addEventListener("wheel", (event) => {
  const delta = Math.sign(event.deltaY);
  console.info(delta);
});

to call addEventListener to listen to the 'wheel' event.

In the event listener, we call Math.sign with event.deltaY to get -1 if we’re scrolling down and 1 if we’re scrolling up.

Conclusion

To listen for the mouse wheel event in modern browsers with JavaScript, we listen to the wheel event.

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 *