Home > Article > Web Front-end > How to Detect and Handle Mouse Wheel Events in jQuery?
Mouse Wheel Event Handling in jQuery
While jQuery provides robust support for handling various user events, including scroll events, you may encounter the need to specifically capture mouse wheel events. This can be useful, for instance, when implementing mouse-driven UI features or custom scroll functions.
jQuery Mouse Wheel Event:
To handle mouse wheel events in jQuery, you can utilize the mousewheel event binder. This event triggers when a user scrolls with their mouse wheel. The event object (represented as e) includes the property originalEvent.wheelDelta, which provides the direction of the wheel scroll.
Capturing the Wheel Scroll Direction:
By checking the value of originalEvent.wheelDelta / 120, you can determine the scroll direction:
Example Usage:
To demonstrate how to implement mouse wheel event handling, consider the following jQuery code:
$(document).ready(function(){ $('#foo').bind('mousewheel', function(e){ if(e.originalEvent.wheelDelta /120 > 0) { console.log('scrolling up !'); } else{ console.log('scrolling down !'); } }); });
In this example, we bind the mousewheel event to an element with the ID "foo." When the user scrolls the mouse wheel over this element, the event handler is triggered and logs the scroll direction to the console.
The above is the detailed content of How to Detect and Handle Mouse Wheel Events in jQuery?. For more information, please follow other related articles on the PHP Chinese website!