Home  >  Article  >  Web Front-end  >  How to Detect Mouse Wheel Events in jQuery?

How to Detect Mouse Wheel Events in jQuery?

Susan Sarandon
Susan SarandonOriginal
2024-10-26 06:34:02993browse

How to Detect Mouse Wheel Events in jQuery?

Retrieving Mouse Wheel Events in jQuery

Beyond the standard scroll events, jQuery provides a mechanism to capture mouse wheel events explicitly. These events offer precise information on the mouse wheel's rotational direction.

Solution:

To detect mouse wheel events in jQuery, you can use the mousewheel event handler. Here's an example:

<code class="javascript">$(document).ready(function() {
    $('#foo').bind('mousewheel', function(e) {
        if (e.originalEvent.wheelDelta / 120 > 0) {
            console.log('Scrolling Up!');
        } else {
            console.log('Scrolling Down!');
        }
    });
});</code>

In this code:

  • $(document).ready(function() {...}) ensures the code runs when the document is loaded.
  • $('#foo').bind('mousewheel', function(e) {...}) binds the mousewheel event handler to the element with the ID 'foo'.
  • e.originalEvent.wheelDelta contains the amount of rotation measured in CSS pixels.
  • The conditional statements check the direction of the wheel rotation:

    • Positive values indicate scrolling up.
    • Negative values indicate scrolling down.
  • console.log() outputs the scrolling direction to the console for debugging purposes.

The above is the detailed content of How to Detect Mouse Wheel Events in jQuery?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn