DOMMouseScroll
only works for Firefox.
wheel
seems to work for both Firefox and chrome. What is this? Haven't found docs on this one.
mousewheel
doesn't work for Firefox.
How should I use them, in order to gain best browser-compatibility.
Example given:
document.addEventListener('ScrollEvent', function(e){
DoSomething();
});
The wheel event fires when the user rotates a wheel button on a pointing device (typically a mouse). This event replaces the non-standard deprecated mousewheel event. Note: Don't confuse the wheel event with the scroll event.
The DOM DOMMouseScroll event is fired asynchronously when mouse wheel or similar device is operated and the accumulated scroll amount is over 1 line or 1 page since last event. It's represented by the MouseScrollEvent interface. This event was only implemented by Firefox.
The wheelDelta attribute value is an abstract value which indicates how far the wheel turned. If the wheel has rotated away from the user, it's positive, otherwise negative. This means that the delta value sign is different from DOM Level 3 Event's wheel .
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
and DOMMouseScroll
events are supported, we need a way to instruct the browser to execute only wheel
and not both. Something like the following:if ("onwheel" in window) ...
The above check though, in the case of IE9
and IE10
will fail, because even though these browsers support the wheel
event, they don't have the onwheel
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
and e.detail
is not useful other than helping us determine the direction of the scroll, so in the solution below -1
and 1
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. 😊
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With