W3docs

How to Distinguish Between Left and Right Mouse Click with jQuery

In this tutorial, you will read and learn useful information about the fastest method of distinguishing between left and right mouse click with jQuery.

jQuery can detect mouse clicks, which is necessary for various web apps to know which mouse button is used to trigger a particular functionality.

You can handle the task with the mousedown() method. The event.button property returns 0, 1, or 2 for the left, middle, and right mouse buttons, respectively:

Example: Detecting Left and Right Mouse Clicks

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.0/jquery.min.js"></script>
    <style>
      #divId {
        padding: 100px;
        border: 3px solid red;
        font-size: 30px;
        text-align: center;
      }
    </style>
  </head>
  <body>
    <div id="divId">
      [Click here]
    </div>
    <script>
      $('#divId').mousedown(function(event) {
          switch(event.button) {
            case 0:
              $('#divId').html('Left Mouse button pressed.');
              break;
            case 1:
              $('#divId').html('Middle Mouse button pressed.');
              break;
            case 2:
              event.preventDefault();
              $('#divId').html('Right Mouse button pressed.');
              break;
            default:
              $('#divId').html('You have a strange Mouse!');
          }
        });
    </script>
  </body>
</html>

The mousedown() Method

The jQuery <kbd class="highlighted">mousedown()</kbd> method is used to bind an event handler to the default ‘mousedown’ JavaScript event, which is used to trigger an event. The button property of the event object can then be used to check the respective mouse button. The value of the button property will be 0 for the left button, 1 for the middle button, or 2 for the right button.