How to Use the Mouse Wheel Event in HTML5 Pages
Supporting the mouse wheel can add further interactivity to your HTML5 web pages. Rather than scrolling the page, you could perform a different action such as zooming in or out.
View the mouse wheel demonstration page…
Most browsers support the “mousewheel” event for any element. You can register a handling function which is passed an event object. This exposes a wheelDelta
property; a positive value for scrolling up or a negative value for scolling down. The larger or smaller the value, the bigger the movement.
Unfortunately, there’s one browser which doesn’t support the the “mousewheel” event. You’re wrong: it’s Firefox. Mozilla has implemented a “DOMMouseScroll” event. This passes an event object with a detail
property but, unlike wheelDelta
, it returns a positive value for scrolling down. So, until Mozilla adopt the event, we have a bizarre situation where it’s actually a little easier to code for IE6! That’s not something you hear said every day.
You should also note that Apple disable the scroll wheel in Safari, but support is available in the webkit engine so your code won’t cause any problems.
Adding a mousewheel Event Handler
Let’s add an image to our web page which will zoom in and out in response to the mouse wheel:
<img id="myimage" src="myimage.jpg" alt="my image" />
We can now attach the mousewheel event handler:
var myimage = document.getElementById("myimage");
if (myimage.addEventListener) {
// IE9, Chrome, Safari, Opera
myimage.addEventListener("mousewheel", MouseWheelHandler, false);
// Firefox
myimage.addEventListener("DOMMouseScroll", MouseWheelHandler, false);
}
// IE 6/7/8
else myimage.attachEvent("onmousewheel", MouseWheelHandler);
The Cross-Browser mousewheel Event Handling Function
Our MouseWheelHandler can now determine the wheel movement delta. In this case, we’re going to reverse Firefox’s detail
value and return either 1 for up or -1 for down:
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)));
We can now size the image accordingly. The code below sets a width between 50px and 800px, but you could determine the image’s natural dimensions and use that.
myimage.style.width = Math.max(50, Math.min(800, myimage.width + (30 * delta))) + "px";
return false;
}
Finally, we return false to cancel the standard event which would normally scroll the page.
View the mouse wheel demonstration page…
The code works in every browser, including IE6, 7 and 8, but Safari users won’t see anything happening.
And if you enjoyed reading this post, you’ll love Learnable; the place to learn fresh skills and techniques from the masters. Members get instant access to all of SitePoint’s ebooks and interactive online courses, like HTML5 & CSS3 For the Real World.
Comments on this article are closed. Have a question about HTML? Why not ask it on our forums?