JavaScript - Mouse wheel event
A simple code example to implement mouse wheel event handling in JavaScript.
The HTML has a <div> tag with id "target" to detect mouse wheel events.
<div id="target">0</div>
The CSS sets the size for the mouse wheel target area.
Also specifies text properties to display mouse scroll amount.
#target {
display: flex;
align-items: center;
justify-content: center;
padding: 10px;
color: white;
width: 250px;
height: 250px;
border-radius: 50%;
text-align: center;
cursor: pointer;
user-select: none;
transition: 1s;
background: #4169e1;
font-size: 40px;
}
Selects the target element with querySelector()
and implements the mouse wheel event with addEventListener()
using "wheel".
Uses preventDefault()
to prevent default browser scrolling.
Displays the cumulative mouse scroll amount on the target element.
// Implement mouse wheel event
document.querySelector('#target').addEventListener('wheel', () => {
// Prevent default behavior
event.preventDefault();
// Display current cumulative mouse scroll amount
let num = parseInt(event.target.textContent);
document.querySelector('#target').textContent = num + event.deltaY;
});