Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mousewheel event in modern browsers

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 }); 
like image 509
Jan Turoň Avatar asked Feb 17 '13 21:02

Jan Turoň


People also ask

What is Mousewheel event?

All Implemented Interfaces: Serializable. public class MouseWheelEvent extends MouseEvent. An event which indicates that the mouse wheel was rotated in a component.

How do I make my Mousewheel click?

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.

How do you get the mouse scroll event in react?

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.


1 Answers

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.

like image 165
Lucio Paiva Avatar answered Sep 22 '22 21:09

Lucio Paiva