jQuery – detect Which mouse button is clicked Example

Updated on     Kisan Patel

We can detect Which mouse button is clicked using jQuery mousedown event. The jQuery mousedown event is used to verify the mouse button is pressed.

jQuery $.mousedown() event Example

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
   <title>jQuery Example</title>
   <script type="text/javascript"
      src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
   <script type="text/javascript">
       $(document).ready(function () {
          $('#button').mousedown(function (event) {
                switch (event.which) {
                    case 1:
                        alert('Left Mouse button pressed.');
                        break;
                    case 2:
                        alert('Middle Mouse button pressed.');
                        break;
                    case 3:
                        alert('Right Mouse button pressed.');
                        break;
                    default:
                        alert('You have a strange Mouse!');
                }
            });
       });
   </script>
</head>
<body>
   <button type="button" id="button">Press mouse</button>
</body>
</html>

Here, event.which will give 1, 2 or 3 for left, middle and right mouse buttons respectively.


jQuery

Leave a Reply