Home > Web Front-end > JS Tutorial > How to Distinguish Left and Right Mouse Clicks with jQuery?

How to Distinguish Left and Right Mouse Clicks with jQuery?

DDD
Release: 2024-12-09 12:29:16
Original
127 people have browsed it

How to Distinguish Left and Right Mouse Clicks with jQuery?

How to Differentiate Between Left and Right Mouse Clicks Using jQuery

While the jQuery click event handler responds to both left and right mouse clicks, it lacks a specific option to distinguish between them. However, by utilizing the event.which property introduced in jQuery version 1.1.3, you can easily determine the type of mouse button that triggered the click event.

Specifically, event.which provides the following values for different mouse buttons:

  • 1: Left button
  • 2: Middle button
  • 3: Right button

Using this property, you can construct a jQuery event handler that responds differently based on the clicked button:

$('#element').mousedown(function(event) {
    switch (event.which) {
        case 1:
            // Code to handle left mouse click
            break;
        case 2:
            // Code to handle middle mouse click
            break;
        case 3:
            // Code to handle right mouse click
            break;
        default:
            // Code to handle unexpected mouse button
    }
});
Copy after login

By utilizing the event.which property and the mousedown event handler, you can effectively distinguish between left and right mouse clicks using jQuery, enabling you to implement customized behavior based on the specific mouse button that was pressed.

The above is the detailed content of How to Distinguish Left and Right Mouse Clicks with jQuery?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template