78

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
});
Dan D.
  • 73,243
  • 15
  • 104
  • 123
Jan Turoň
  • 31,451
  • 23
  • 125
  • 169
  • 3
    Chrome and IE support [`MouseWheelEvent`](https://developer.mozilla.org/en-US/docs/DOM/MouseWheelEvent), while Firefox supports [`WheelEvent`](https://developer.mozilla.org/en-US/docs/DOM/WheelEvent). For listening across browser , see [here](https://developer.mozilla.org/en-US/docs/Mozilla_event_reference/wheel#Listening_to_this_event_across_browser). – Derek 朕會功夫 Feb 17 '13 at 21:42
  • 1
    Added to Derek's point. On these cases you should really evaluate browser compatibilities. You can do that with Modernizr (http://www.modernizr.com). It will make your life a lot easier :) –  Feb 17 '13 at 22:49
  • 4
    Nowdays, according to MDN the [wheel](https://developer.mozilla.org/en-US/docs/Web/Events/wheel#Browser_compatibility) event is supported in all modern desktop browsers. – gdros Oct 31 '16 at 20:59

3 Answers3

106

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.

Lucio Paiva
  • 19,015
  • 11
  • 82
  • 104
  • 2
    I'd prefer to keep the absolute value of the wheelDelta to detect speed of scroll. Is there any formula to normalize this among browsers? – Jan Turoň Jul 11 '18 at 08:08
  • Unfortunately, if you want to use the absolute value, there's no formula. You'd have to rely on some sort of table with empirically-obtained values for each browser/OS combination. For regular mice, `wheelDelta` is always fixed no matter how fast you scroll, so it's ok to do what I proposed above. However, if you want to capture sensitivity on a track pad, for instance (I guess that's what you're looking for), then you're own your own. Let's just hope this value gets standardized across browsers in the future. – Lucio Paiva Jul 11 '18 at 13:39
  • 1
    That does throw an alert in the console: `[Violation] Added non-passive event listener to a scroll-blocking 'wheel' event. Consider marking event handler as 'passive' to make the page more responsive. See` https://www.chromestatus.com/feature/5745543795965952 – Derk Jan Speelman Sep 09 '18 at 19:45
  • Interesting. I'm using Chrome 68 and am not seeing this alert. @DerkJanSpeelman Are you sure you're testing the exact same code as above? I just tried both versions (with and without delta sign extraction) but could not reproduce what you're seeing. – Lucio Paiva Sep 09 '18 at 20:20
  • @LucioPaiva I was on an older version indeed. But after I updated I still see the same alert. Here's my code: `window.onwheel = () => { let delta = Math.sign(event.wheelDelta); console.log(delta) }`. I also see the same alert when I simply copy the code example in this answer. – Derk Jan Speelman Sep 09 '18 at 20:32
  • 1
    I'm still unable to reproduce it here. Maybe different operating systems? I'm trying it on Ubuntu 18.04. Also, are you running any extra code at the same time? Anyway, MDN [mentions](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener) that passing a third parameter `{ passive: true }` to `addEventListener()` solves the problem in case you don't need to `event.preventDefault()`. If you do, it looks like there's [not much you can do](https://developers.google.com/web/tools/lighthouse/audits/passive-event-listeners) (check people complaining in the comments). – Lucio Paiva Sep 09 '18 at 20:55
  • i dont have event.delta, it's null, why? – Dee Jul 18 '19 at 05:44
  • @datdinhquoc many things could be wrong. You should post a new question stating your browser and showing some code so that others can help. – Lucio Paiva Jul 18 '19 at 10:16
  • @LucioPaiva i had to use event.originalEvent.deltaY – Dee Jul 18 '19 at 23:19
  • Use deltaMode. This is the only way to have an interoperable scrolling. – karlcow Jun 02 '20 at 08:30
57

Here's an article that describes this, and gives an example:

http://www.sitepoint.com/html5-javascript-mouse-wheel/

Relevant code, minus the specific example given of resizing an image:

var myitem = document.getElementById("myItem");
if (myitem.addEventListener)
{
    // IE9, Chrome, Safari, Opera
    myitem.addEventListener("mousewheel", MouseWheelHandler, false);
    // Firefox
    myitem.addEventListener("DOMMouseScroll", MouseWheelHandler, false);
}
// IE 6/7/8
else
{
    myitem.attachEvent("onmousewheel", MouseWheelHandler);
}

function MouseWheelHandler(e)
{
    // cross-browser wheel delta
    var e = window.event || e; // old IE support
    var delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail)));

    return false;
}
Almo
  • 15,538
  • 13
  • 67
  • 95
  • 1
    Excellent answer. Needs more attention. Many uncomplete answers on this issue, – Terrance00 Feb 07 '17 at 06:16
  • This appears to be a deprecated event and has been removed from many browsers. The event to use now is a "WheelEvent" (https://developer.mozilla.org/en-US/docs/Web/API/WheelEvent) – dug Dec 28 '19 at 02:52
  • This is useful for older browser support, specifically IE does not support Math.sign at all, but Math.max and Math.min are supported. https://caniuse.com/?search=Math.sign – ryancdotnet Sep 08 '20 at 03:17
8

This will work in Firefox, Chrome and Edge too:

window.addEventListener("wheel", function(e) {
    var dir = Math.sign(e.deltaY);
    console.log(dir);
});
Iter Ator
  • 8,226
  • 20
  • 73
  • 164