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 });
All Implemented Interfaces: Serializable. public class MouseWheelEvent extends MouseEvent. An event which indicates that the mouse wheel was rotated in a component.
On a mouse with a scroll wheel, you can usually press directly down on the scroll wheel to middle-click. If you don't have a middle mouse button, you can press the left and right mouse buttons at the same time to middle-click.
To listen for mouse wheel events in React, we can set the onWheel prop to the mouse wheel event listener. We set onWheel to a function that logs the event object. Now when we scroll up and down with the mouse wheel, we should see the event object logged.
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.
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