jQuery

How To Detect Which Mouse Button Click Using jQuery

In this blog we will learn How To Detect Which Mouse Button Click Using jQuery.

How To Detect Which Mouse Button Click Using jQuery
This will help you to detect the left,middle and right mouse click events using Jquery. I have tested below code in IE, Firefox and Google chrome also.

In below example we have attached mouseup event on button element. When the mouse button is click over the button element, and the mouse button is pressed, event.which property returns which mouse button was pressed for the event.

Syntax:

event.which

Before learn How To Detect Which Mouse Button Click Using jQuery. First know about event

event : The event parameter comes from the event binding function.

Code :

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title></title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <script type="text/javascript">
      $(document).ready(function () {
          $('#btnclick').mouseup(function (event) {
              var button = '';
              switch (event.which) {
                  case 1: button = "Left Button click"; break;
                  case 2: button = "Midde Button click"; break;
                  case 3: button = "Right Button click"; break;
                  default: button = "Invalid button click "; break;
              }
              $('#divresult').html(button);
          });
      })

  </script>
    <style>
        .button1 {
            background-color: #4CAF50;
            border: none;
            color: white;
            padding: 15px 32px;
            text-align: center;
            text-decoration: none;
            display: inline-block;
            font-size: 16px;
            margin: 4px 2px;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <input type="button" id="btnclick" value="Clck Me" class="button1" />
    <br /><br />
    <div id="divresult"></div>
</body>
</html>

Output :
detect-mouse-button-click-using-jquery

detect-mouse-button-click-using-jquery

detect-mouse-button-click-using-jquery

Leave a Reply

Your email address will not be published. Required fields are marked *