The HTML onwheel attribute is an event handler that triggers the script to execute when the wheel of a pointing device (such as a mouse wheel or a touchpad for scrolling/zooming) is rolled up or down over a specific element.
Definition and Usage
➔ This is a modern replacement for the deprecated onmousewheel attribute.
➔ When the onwheel event is fired, it passes a WheelEvent object that has several properties:
- deltaX: The horizontal scroll amount of the wheel.
- deltaY: The vertical scroll amount of the wheel (positive value to scroll down, negative to scroll up).
- DeltaZ: The amount of scroll on the z-axis.
- DeltaMode: The unit of measurement for delta values (such as 0-pixels, 1-lines, or 2-pages).
➔ onwheel is about the action of the input device, while onscroll is about the action of the scroll position of the element.
Syntax
//In HTML
<div class="myDIV" onwheel="myFunction(event)" id="sample">
Roll your mouse wheel over this box.
</div>
//In javascript
document.getElementById("sample").onwheel=function() {myFunction();};
//OR
document.getElementById("sample").addEventListener("wheel", myFunction);
//OR
document.getElementById("sample").addEventListener("wheel", (event) => {
myFunction();
});
Applies to
This attribute can be used on the following element.
| Attribute | Element |
|---|---|
| onwheel | All visible elements |
Example
<!DOCTYPE html>
<html>
<head>
<title>HTML onwheel Attribute Example</title>
<meta charset="utf-8" />
<style>
.myDIV {
border: 2px dashed black;
width: 250px;
text-align: center;
padding: 50px;
background-color: lightskyblue;
}
</style>
</head>
<body>
<h2>HTML onwheel Attribute Example</h2>
<p>Try Roll your mouse wheel over this box div element to fire event.</p>
<div class="myDIV" onwheel="myFunction(event)">
Roll your mouse wheel over this box.
</div>
<p id="output">Scroll amount (deltaY): 0</p>
<script>
function myFunction(event) {
// Preventing the default scroll behavior for the page
event.preventDefault();
//Vertical Scroll(positive for down, negative for up)
//Scroll Mode(0:PIXEL, 1:LINE, 2:PAGE)
var scrollAmountX = event.deltaX;
var scrollAmountY = event.deltaY;
var scrollAmountZ = event.deltaZ;
var scrollMode = "";
switch (event.deltaMode) {
case 0:
scrollMode = "PIXEL (0)";
break;
case 1:
scrollMode = "LINE (1)";
break;
case 2:
scrollMode = "PAGE (2)";
break;
}
var txt = "Scroll amount (deltaX): " + scrollAmountX +
"<br>Scroll amount (deltaY): " + scrollAmountY +
"<br>Scroll amount (deltaZ): " + scrollAmountZ +
"<br>Scroll Mode(deltaMode): " + scrollMode;
document.getElementById("output").innerHTML = txt;
}
</script>
</body>
</html>
Click on the "Try it Now" button to see how it works.