H3XED

JavaScript - How To Get Mouse Scroll Wheel Events in Both Firefox and Chrome

Feb 18, 2014   Programming   Nick Vogt   Comments (2)
Please note that this post is over a year old and may contain outdated information.
Firefox and Chrome use two different JavaScript events for the mouse wheel, and the delta attribute is under a different name in each. Fortunately, there is a simple work-around that will be sufficient in most situations:

// For Chrome
window.addEventListener('mousewheel', mouseWheelEvent);

// For Firefox
window.addEventListener('DOMMouseScroll', mouseWheelEvent);

function mouseWheelEvent(e) {
    var delta = e.wheelDelta ? e.wheelDelta : -e.detail;
}

Modern Firefix utilizes the DOMMouseScroll event with the detail attribute, while Chrome uses the mousewheel event with the wheelDelta attribute. The two attributes are also opposite sign of each other, so you must negate one of them. The above code does just that, using a single-line ternary to detect which attribute exists.

This unfortunately does not equalize the delta speed of each. For example, you may get 120 or -120 on Chrome, but only 5 or -5 on Firefox. It at least gets you the correct movement direction of the mouse wheel.
Share This Post
Twitter

Comments (2)

Moacir Fhr   Feb 08, 2017
You save my life, man! Thanks!
Louis Ameline   Feb 05, 2017
In 2017, you should write something like: window.addEventListener('wheel', function(event){ if(event.deltaY 0){ // wheeled up } else { // wheeled down } }); Compatible with Chrome 56, Firefox 51, IE9+.
Share This Post
Twitter
H3XED © Nick Vogt   RSS   Policies   Twitter