How to detect left mouse click and right mouse click with jQuery

How to detect left mouse click and right mouse click with jQuery

If you want to implement a javascript interface probably you will get to a point where you have to know witch button was pressed. The next code will detect correctly for IE, Firefox, Chrome, Opera and Safari.


/* this will append click detection to whole document
 * if you want to add this feature just on one area
 * just change the selector for the jQuery
 */
jQuery(document).click(function(event) {
   if (jQuery.browser.msie){
      if (event.which < 2){
         alert('Left button');
      }
   }else
   switch (event.which) {
      case 1:
         alert('Left button');
         break;
      case 2:
         alert('Middle button');
         break;
      case 3:
         alert('Right button');
         break;
      default:
         alert('unknown');
   }

});


above script work ok on Firefox and detect Left Mouse click in Chrome and IE, however Right mouse click is not detected in Chrome/IE because context menu is fired first.

To disable context menu just add the next code. Do not forget to add selector for the area you need it. And is better to add the right click code to this function instead the above one.


jQuery(document).bind('contextmenu', function(e){
   e.preventDefault();
   console.log("Right button");
   return false;
});

No comments.