mousewheel,wheel and DOMMouseScroll in JavaScript
In case your goal would be prevent scrolling up and down, but browser gives you error due to DOM level is passive, just pass {passive: false} as the third argument within .addEventListener method:
// Solution to this: https://www.chromestatus.com/features/6662647093133312
window.addEventListener("wheel", function (e) {e.preventDefault()}, {passive: false}); // no more mouse wheel scrolling [both sides]
// window.addEventListener("wheel", function (e) {e.preventDefault()}, {passive: true}); this is default behaviour
I would suggest that all three of them be used at the same time to cover all browsers.
Notes:
In versions of Firefox where both the
wheel
andDOMMouseScroll
events are supported, we need a way to instruct the browser to execute onlywheel
and not both. Something like the following:if ("onwheel" in window) ...
The above check though, in the case of
IE9
andIE10
will fail, because even though these browsers support thewheel
event, they don't have theonwheel
attribute in DOM elements. To counter that we can use a flag as shown later on.I believe the number returned by
e.deltaY
,e.wheelDelta
ande.detail
is not useful other than helping us determine the direction of the scroll, so in the solution below-1
and1
will be returned.
Snippet:
/* The flag that determines whether the wheel event is supported. */
var supportsWheel = false;
/* The function that will run when the events are triggered. */
function DoSomething (e) {
/* Check whether the wheel event is supported. */
if (e.type == "wheel") supportsWheel = true;
else if (supportsWheel) return;
/* Determine the direction of the scroll (< 0 → up, > 0 → down). */
var delta = ((e.deltaY || -e.wheelDelta || e.detail) >> 10) || 1;
/* ... */
console.log(delta);
}
/* Add the event listeners for each event. */
document.addEventListener('wheel', DoSomething);
document.addEventListener('mousewheel', DoSomething);
document.addEventListener('DOMMouseScroll', DoSomething);
Although almost 3 years have passed since the posting of the question, I believe people who stumble upon it in the future will benefit from this answer, so feel free to suggest/make improvements to it. ð