Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery: detect if middle or right mouse button is clicked, if so, do this:

Check out my jsfiddle demo, if e.which == 1 then when you left click the h2 it will e.which == 2 or e.which == 3 then it wont work. 2 is the middle mouse button, and 3 is the right mouse button. i found this too:

JQuery provides an e.which attribute, returning 1, 2, 3 for left, middle, and right click respectively. So you could also use if (e.which == 3) { alert("right click"); }

This code isn't working:

code:

    $("h2").live('click', function(e) { 
   if( e.which == 2 ) {
      e.preventDefault();
      alert("middle button"); 
   }
});
like image 715
android.nick Avatar asked Oct 24 '10 08:10

android.nick


People also ask

How does jQuery detect right click?

oncontextmenu = function() {return false;}; $(document). mousedown(function(e){ if( e. button == 2 ) { alert('Right mouse button! '); return false; } return true; }); });

How can you tell if a mouse is left or right jQuery?

Using the mousedown() method: The mousedown() method in jQuery can be used to bind an event handler to the default 'mousedown' JavaScript event. This can be used to trigger an event. The event object's 'which' property can then used to check the respective mouse button.

What is the difference between Mousedown and click?

Note: This differs from the click event in that click is fired after a full click action occurs; that is, the mouse button is pressed and released while the pointer remains inside the same element. mousedown is fired the moment the button is initially pressed.


2 Answers

You may want to trap the mousedown event, and you also need to prevent the oncontextmenu event to stop the context menu from coming up during the right click event.

$("h2").live('mousedown', function(e) { 
   if( (e.which == 1) ) {
     alert("left button");
   }if( (e.which == 3) ) {
     alert("right button");
   }else if( (e.which == 2) ) {
      alert("middle button"); 
   }
   e.preventDefault();
}).live('contextmenu', function(e){
   e.preventDefault();
});

UPDATE: .live() has been deprecated since jQuery 1.9. Use .on() instead.

$("h2").on('mousedown', function(e) { 
  if (e.which == 1) {
    alert("left button");
  } else if (e.which == 3) {
    alert("right button");
  } else if (e.which == 2) {
    alert("middle button");
  }
  e.preventDefault();
});
like image 199
burntblark Avatar answered Oct 14 '22 21:10

burntblark


I've noticed some oddities in the past with using the click event for anything but a regular left-click. I don't recall the details, but if you change "click" to "mousedown" or "mouseup" you should have better results.

like image 29
Rebecca Chernoff Avatar answered Oct 14 '22 21:10

Rebecca Chernoff