How to detect left right mouse click using Jquery

How to detect left right mouse click using Jquery

By Yashwant Chavan, Views 1228, Date 30-Sep-2015

Just want to share my latest Jquery post , which will help you to detect the left and right mouse click events using Jquery. I have tested below code in IE 11.0.96, Firefox and Google chrome also,

tags jquery mouse-click

In below example we have attached mousedown event on div element. When the mouse pointer is over the element, and the mouse button is pressed. Then with the help of event.which we will figure out which mouse button is pressed.

It is used for key or mouse events, this property indicates the specific key or button that was pressed, Here is mapping for each buttons 1 for left button, 2 for middle, and 3 for right button.

<!DOCTYPE html>
<html>
   <head>
      <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>  
      <script>
         $(document).ready(function(){         
          $('.box').mousedown(function(event) {  
           switch (event.which) {
           case 1:
            $("p").html("Left Mouse Clicked");
            break;
           case 2:
            $("p").html("Middle Mouse Clicked");
            break;
           case 3:
            $("p").html("Right Mouse Clicked");
            break;
           default:
            $("p").html("Option Not Found..");
           }
          });
         });  
      </script>     
   </head>
   <style>
      .box{  
      height:200px;
      width:200px;  
      padding:10px;
      margin:10px;  
      display:inline-block;
      background:#ff9900;  
      } 
      p{ 
      margin:10px;
      font-weight:bold;
      }
   </style>
   <body>
      <h1>Detect left, right mouse click using Jquery</h1>
      <div id="container">
         <div class="box" id="box"></div>
         <p></p>
      </div>
   </body>
</html>

Output

How to detect left right mouse click using Jquery

Finish

Hope this Tutorial is useful to you, Please fill free to provide your comments if there is any problem. Thanks

Yashwant

Yashwant

Hi there! I am founder of technicalkeeda.com and programming enthusiast. My skills includes Java,J2EE, Spring Framework, Nodejs, PHP and lot more. If you have any idea that you would want me to develop? Lets connect: yashwantchavan[at][gmail.com]