To detect mouse wheel events in JavaScript, you can use the addEventListener()
method to register a function that will be called whenever a “wheel” event is fired. Here’s an example:
// Register an event listener for the "wheel" event
document.addEventListener('wheel', function(event) {
// Do something with the event
});
In the above example, the addEventListener()
method registers a function that will be called whenever a “wheel” event is fired on the document
object. The function receives the event
object as an argument, which contains information about the event, such as the type of event, the target element, and any other relevant details.
Inside the function, you can access the event.deltaY
property to get the distance that the mouse wheel was rotated. This property returns a positive value if the wheel was rotated upwards or away from the user, and a negative value if the wheel was rotated downwards or towards the user. Here’s an example:
document.addEventListener('wheel', function(event) {
// Get the distance that the mouse wheel was rotated
const delta = event.deltaY;
// Check the value of delta
if (delta > 0) {
// The wheel was rotated upwards or away from the user
} else if (delta < 0) {
// The wheel was rotated downwards or towards the user
}
});
In the above example, the event.deltaY
property is used to determine the direction that the mouse wheel was rotated, and the appropriate action is taken based on that value.