HTML onwheel Event Attribute

If this site has been useful, we’d love your support! Running this site takes time and resources, and every small contribution helps us keep creating valuable content. Consider buying us a coffee to keep things going strong!

Description

The onwheel HTML event attribute specifies a JavaScript function to be executed when the user scrolls the mouse wheel or uses a touchpad to scroll or zoom over an element.

The onwheel event is supported by all major browsers, including Chrome, Firefox, Edge, Safari, and Opera.

To use the onwheel event attribute, simply add it to the element you want to respond to the event. For example, the following code will execute the myFunction() function when the user scrolls the mouse wheel over the <div> element:

<div onwheel="myFunction()">
  This is the content of the div element.
</div>

The myFunction() function can then use the event object to access information about the event, such as the direction of the scroll and the amount of scrolling that occurred.

Here is an example of a simple myFunction() function that logs the direction of the scroll to the console:

function myFunction(event) {
  if (event.deltaY < 0) {
    console.log("Scrolling up");
  } else if (event.deltaY > 0) {
    console.log("Scrolling down");
  }
}

The onwheel event attribute can be used to create a variety of interactive effects, such as zooming in and out of images, scrolling through lists of items, and changing the state of a graphical user interface.

Here are a few examples of how the onwheel event attribute can be used:

  • Create a zoom slider that allows users to zoom in and out of an image by scrolling the mouse wheel.
  • Create a carousel that allows users to scroll through a list of items by scrolling the mouse wheel.
  • Create a dropdown menu that opens and closes when the user scrolls the mouse wheel over the dropdown button.
  • Create a video player that allows users to pause and play the video by scrolling the mouse wheel.

Syntax

<element onwheel="script">

Values

  • scriptThe name of the script to use when the event has been triggered.

Example

<!DOCTYPE html> 
<html>
<head>
<title>onwheel event</title>
<style>
div {
border: 1px solid;
}
</style>
</head>
<body>
<p>To demonstrate the onwheel event attribute, use the mouse wheel on the element:</p>
<div id="wheeee" onwheel="wheeee()">The quick brown fox jumps over the lazy dog</div>
<script>
function wheeee () {
document.getElementById("wheeee").style.fontSize="35px";
document.getElementById("wheeee").style.color="blue";
}
</script>
</body>
</html>

Browser Support

The following table will show you the current browser support for the HTML onwheel Event Attribute.

Desktop
Edge Chrome Firefox Opera Safari
YesYesYesYesYes
Tablets / Mobile
Chrome Firefox Opera Safari Samsung Webview
YesYesYesYesYesYes

Last updated by CSSPortal on: 13th October 2023