Mousewheel event in modern browsers

Jan Turoň picture Jan Turoň · Feb 17, 2013 · Viewed 75.4k times · Source

I'd like to have clean and nice JavaScript for mousewheel event, supporting only the latest version of common browsers without legacy code for obsolete versions, without any JS framework.

Mousewheel event is nicely explained here. How to simplify it for the current latest versions of the browsers?

I don't have access to all browsers to test it, so caniuse.com is a great help to me. Alas, mousewheel is not mentioned there.

Based on Derek's comment, I wrote this solution. Is it valid for all browsers?

someObject.addEventListener("onwheel" in document ? "wheel" : "mousewheel", function(e) {
  e.wheel = e.deltaY ? -e.deltaY : e.wheelDelta/40;
  // custom code
});

Answer

Lucio Paiva picture Lucio Paiva · Jul 11, 2018

Clean and simple:

window.addEventListener("wheel", event => console.info(event.deltaY));

Browsers may return different values for the delta (for instance, Chrome returns +120 (scroll up) or -120 (scroll down). A nice trick to normalize it is to extract its sign, effectively converting it to +1/-1:

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

Reference: MDN.