Mousewheel event in modern browsers

JavascriptMousewheel

Javascript Problem Overview


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
});

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

Here's an article that describes this, and gives an example:

http://www.sitepoint.com/html5-javascript-mouse-wheel/

Relevant code, minus the specific example given of resizing an image:

var myitem = document.getElementById("myItem");
if (myitem.addEventListener)
{
	// IE9, Chrome, Safari, Opera
	myitem.addEventListener("mousewheel", MouseWheelHandler, false);
	// Firefox
	myitem.addEventListener("DOMMouseScroll", MouseWheelHandler, false);
}
// IE 6/7/8
else
{
    myitem.attachEvent("onmousewheel", MouseWheelHandler);
}

function MouseWheelHandler(e)
{
	// cross-browser wheel delta
	var e = window.event || e; // old IE support
	var delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail)));

	return false;
}

Solution 3 - Javascript

This will work in Firefox, Chrome and Edge too:

window.addEventListener("wheel", function(e) {
    var dir = Math.sign(e.deltaY);
    console.log(dir);
});

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJan TuroňView Question on Stackoverflow
Solution 1 - JavascriptLucio PaivaView Answer on Stackoverflow
Solution 2 - JavascriptAlmoView Answer on Stackoverflow
Solution 3 - JavascriptIter AtorView Answer on Stackoverflow