The HTML onwheel event
The HTML onwheel attribute runs JavaScript when the user rotates a mouse or touchpad wheel over the element. It is an inline handler for the wheel event; in modern code prefer addEventListener('wheel', …).
Overview
The onwheel event attribute runs JavaScript when the wheel is scrolled over the element. In JavaScript the event itself is named wheel. Drop the on prefix when you call addEventListener.
It is a mouse-family event, but its handler receives a WheelEvent, whose deltaX, deltaY and deltaMode describe how far and in what units the wheel moved, alongside the usual pointer coordinates and modifier keys. Pointer events replace the other mouse events, but there is no pointer equivalent for the wheel.
You can wire this up with the inline onwheel HTML attribute, but the modern, recommended approach is element.addEventListener('wheel', handler) in JavaScript. That keeps behavior out of your markup, lets you attach several handlers to the same event, and makes them easy to remove. The inline attribute is fine for quick demos.
Syntax
<element onwheel="handler()">…</element>
element.addEventListener('wheel', handler);
Best practices
- Prefer
element.addEventListener('wheel', handler)over the inlineonwheelattribute; it separates behavior from markup and allows multiple handlers. - Build interactivity on real <button> or link elements so it also works with the keyboard, not on mouse events alone.
- Consider the unified pointer events to handle mouse, touch and pen together.
- Read coordinates and the pressed button from the
MouseEventthe handler receives.
Frequently asked questions
What is the onwheel event?
wheel.Does this event work on touch screens?
scroll (and pointer) events rather than wheel, and pointer events have no wheel equivalent, so listen for scroll if you care about scrolling however it happens.How much did the wheel move?
event.deltaY (and event.deltaX), interpreting them with event.deltaMode, which says whether the values are pixels, lines or pages.Should I use the onwheel attribute or addEventListener?
element.addEventListener('wheel', …) in JavaScript. The inline onwheel attribute works but mixes behavior into the markup and allows only one handler per element.