YouTip LogoYouTip

Event Onwheel

## JavaScript DOM `onwheel` Event The `onwheel` event fires when the user rotates a mouse wheel or slides a trackpad over an element. This event can also be triggered by pinch-to-zoom gestures on trackpads (such as those on laptops). --- ## Syntax and Usage You can register a wheel event handler in three ways: via HTML attributes, direct DOM property assignment, or using the standard `addEventListener()` method. ### 1. In HTML ```html ``` ### 2. In JavaScript (DOM Property) ```javascript object.onwheel = function() { myScript(); }; ``` ### 3. In JavaScript (Event Listener) ```javascript object.addEventListener("wheel", myFunction); ``` > **Note:** When using `addEventListener()`, pass the event name as `"wheel"` (without the `"on"` prefix). --- ## Code Examples ### Example 1: Basic Usage with `addEventListener` This example changes the text color of a `
` element to red when the user scrolls the mouse wheel over it. ```html
Scroll your mouse wheel over me!
``` ### Example 2: Reading Scroll Direction and Delta Values The `wheel` event passes a `WheelEvent` object to the handler. You can use properties like `deltaY` to determine whether the user is scrolling up or down. ```javascript const box = document.getElementById("myDIV"); box.addEventListener("wheel", function(event) { // Prevent the default page scroll behavior if necessary event.preventDefault(); if (event.deltaY < 0) { console.log("Scrolling UP"); } else if (event.deltaY > 0) { console.log("Scrolling DOWN"); } }); ``` --- ## Technical Details | Feature | Support / Value | | :--- | :--- | | **Bubbles** | Yes | | **Cancelable** | Yes | | **Event Interface** | `WheelEvent` | | **Supported HTML Tags** | All HTML elements | --- ## Browser Compatibility | Event | Chrome | Internet Explorer / Edge | Firefox | Safari | Opera | | :--- | :--- | :--- | :--- | :--- | :--- | | `onwheel` | 31.0+ | 9.0+ | 17.0+ | 6.0+ | 18.0+ | ### Compatibility Notes: * **Internet Explorer:** In IE, the `wheel` event is only supported via the `addEventListener()` method. The `onwheel` property does not exist directly on DOM objects in older IE versions. * **Legacy Browsers:** Internet Explorer 8 and earlier versions do not support `addEventListener()`. * **Legacy Events:** The standard `wheel` event replaces the older, non-standard `mousewheel` and `DOMMouseScroll` events. For modern web development, always prefer the standard `wheel` event.
← Av Event AbortEv Onshow β†’