jbyrd
jbyrd

Reputation: 5585

Can't use jquery's click event handler to detect right click

In trying to detect a right mouse click with jquery, I noticed that the click event handler doesn't seem to be fired off with a right mouse click, while the mousedown or mouseup event handler's do.

For example, after a right click on the test div, the following alerts 'testing!':

$('#test').mousedown(function(e) {
    alert('testing');
});

However, the following does not:

$('#test').click(function(e) {
    alert('testing!');
});

Does anyone know why?

Upvotes: 6

Views: 10918

Answers (4)

sabertooth1990
sabertooth1990

Reputation: 1086

I have also tried the following code to catch right mouse click for certain class of elements

$(".brick").mousedown(function (event) {
            if (event.which === 3) {
                currentRightClickedTileID = $(this).attr("id");
            }
        });

This code doesn't always catch the right click.

Upvotes: 0

htanata
htanata

Reputation: 36944

As this article puts it:

There are no click events for right button clicks in any browser.

So you're left with mousedown and mouseup in most browsers.

Upvotes: 8

nnnnnn
nnnnnn

Reputation: 150020

Not sure which browser(s) you've tested with, but according to MSDN the onclick fires "when the user clicks the left mouse button". I.e., by definition it doesn't occur for right (or middle) clicks. Given that's on MSDN you can expect IE to behave that way regardless of what the other browsers do.

(Onclick also fires for certain non-mouse things, like changing certain form elements with the keyboard, etc.)

I know jQuery tries to normalise behaviour between browsers, but if the browser doesn't fire the event at all...

There is at least one jQuery plugin that I know of that implements right-click: http://abeautifulsite.net/blog/2008/05/jquery-right-click-plugin/ (I haven't used it, but it looks good except that it notes that Opera doesn't support it).

Upvotes: 0

wesbos
wesbos

Reputation: 26317

When you mousedown, the even fired has event.which

Taken from here: How to distinguish between left and right mouse click with jQuery

$('#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');
    }
});

So instead of using .click(), use mousedown and check for the cases.

Upvotes: 12

Related Questions