views:

6832

answers:

4

Hello,

What is the way of understanding the clicked mouse button with jquery or with javascript?

$('div').bind('click', function(){
    alert('clicked');
});

this fetches both right and left click, what is the way of being able to catch rightclick? I'd be happy if sth like below exists:)

$('div').bind('rightclick', function(){ 
    alert('right mouse button is pressed');
});

Thanks, Sinan.

+11  A: 

from a beautiful site:

$("#element").live('click', function(e) {
  if( (!$.browser.msie && e.button == 0) || ($.browser.msie && e.button == 1) ) {
       alert("Left Button");
    }
    else if(e.button == 2){
       alert("Right Button");
    }
});
TheVillageIdiot
Thanks the thing i needed was that e.button == 0,1 etc.
Sinan Y.
is this msie-specific? ie is it portable across other browsers?
Taryn East
This method is now unnecessary as `event.which` has been introduced which eliminates cross browser compatibility.
Acorn
Dear @Acorn thanks for comment
TheVillageIdiot
+10  A: 

The jQuery Right-Click plugin is designed to make that simpler

karim79
Thanks this is also very useful.
Sinan Y.
+1, It's usually better to use a plugin. Also, I can't see 9998.
Kobi
@Kobi, what do you mean with 9998?
Sinan Y.
@Kobi @Sinan - Kobi pushed me into the 10k rep zone with his upvote, thanks Kobi.
karim79
Sorry, nothing technical. I jumped his/her reputation from 9998 to 10K. That plugin does help, though.
Kobi
ok, my congrats on that :)
Sinan Y.
+2  A: 

It seems to me that a slight adaptation of TheVillageIdiot's answer would be cleaner:

$('#element').bind('click', function(e) {
  if (e.button == 2) {
    alert("Right click");
  }
  else {
    alert("Some other click");
  }
}

EDIT: 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"); }

See also: answers to "Triggering onclick event using middle click"

Dan
Thanks for e.which +1
Sinan Y.
+11  A: 

As of jQuery version 1.1.3 event.which normalizes event.keyCode and event.charCode so you don't have to worry about browser compatibility. Documentation on event.which

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

$('#element').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');
    }
});
Acorn
Thanks, didn't know that...
Sinan Y.