Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why right click is not triggered with .click()?

This is a simple code :

HTML

<a id="link" href="#">Ciao</a>

jQuery

$('#link').click(function () {
    alert("ciao");
});

in fact, left/middle button is triggered (the alert is printed) but with Right Click? Why not? And how can I trigger it?

like image 832
markzzz Avatar asked Dec 05 '22 18:12

markzzz


2 Answers

Bind mousedown to handle left, middle and right clicks:

$('#link').mousedown(function(e) {
   alert("ciao");
});

You can use e.which to determinate which button has been clicked. 1: left, 2: middle and 3: right.

Here's the demo: http://jsfiddle.net/fPhDg/9/


You can stop the contextmenu from appearing like this:

$('#link').contextmenu(false);

Demo: http://jsfiddle.net/y4XDt/

You should use this very very carefully! It only makes sense in some very rare cases.

like image 123
js-coder Avatar answered Dec 07 '22 08:12

js-coder


Use .contextmenu(...):

$('#link').contextmenu(function () {
    alert("ciao");
});

And if you want to catch both events, you could use the bind(...) function:

$('#link').bind('click contextmenu',function()
{
    alert("ciao");
});

http://jsfiddle.net/fPhDg/4/

like image 37
ComFreek Avatar answered Dec 07 '22 07:12

ComFreek