Mousewheel event in modern browsers
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.
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;
}