How to distinguish left and right mouse click using jQuery?

jQuery can be used to distinguish which mouse button is being clicked. This can be used in various web applications where knowing a certain mouse button can be used to trigger certain functionality.

Using the mousedown() method:

The mousedown() method in jQuery can be used to bind an event handler to the default ‘mousedown’ JavaScript event. This can be used to trigger an event. The event object’s ‘which’ property can then used to check the respective mouse button.

Syntax:

$( "#target" ).mousedown(function() {
  alert( "Function to be handles here" );
});

“which” property:
The which property has 3 values depending on the mouse button pressed. We can use a switch case to get the corresponding value.

  • 1 for the left mouse button
  • 2 for the middle mouse button
  • 3 for the right mouse button

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html lang="en">
  
<head>
    <title>
      How to distinguish left and right 
      mouse click using jQuery?
  </title>
</head>
  
<body>
    <h1 style="color: green">
      GeeksforGeeks
  </h1>
    <b>
      How to distinguish left and 
      right mouse click using jQuery?
  </b>
    <p>You are pressing the :
        <div class="output">
  </div>
  
    <button>
      Click Here to check the mousebutton pressed
  </button>
  </script>
    
    <script type="text/javascript">
        $('button').mousedown(function(event) {
            switch (event.which) {
                case 1:
                    document.querySelector('.output').innerHTML =
                        'Left Mouse Button';
                    break;
                case 2:
                    document.querySelector('.output').innerHTML =
                        'Middle Mouse Button';
                    break;
                case 3:
                    document.querySelector('.output').innerHTML =
                        'Right Mouse Button';
                    break;
                default:
                    break;
            }
        });
    </script>
</body>
  
</html>

chevron_right


Output:
Clicking with the left mouse button:
left-button

Clicking with the middle mouse button:
middle-button

Clicking with the right mouse button:
right-button



My Personal Notes arrow_drop_up

Technical Writer Lets have an update

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.