How to Distinguish Between Left and Right Mouse Click with jQuery

jQuery can detect mouse click 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 and event which. event.which will give 1, 2 or 3 for left, middle and right mouse buttons, respectively:

<!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.which) {
            case 1:
              $('#divId').html('Left Mouse button pressed.');
              break;
            case 2:
              $('#divId').html('Middle Mouse button pressed.');
              break;
            case 3:
              $('#divId').html('Right Mouse button pressed.');
              break;
            default:
              $('#divId').html('You have a strange Mouse!');
          }
        });
    </script>
  </body>
</html>

The mousedown() Method

The jQuery mousedown() method is used to bind an event handler to the default ‘mousedown’ JavaScript event, which is used to trigger an event. The ‘which’ property of the event object can then be used to check the respective mouse button. The value of “which” property will be 1 for the left button, 2 for the middle button, or 3 for the right button.

Do you find this helpful?

Related articles