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

jbyrd picture jbyrd · Sep 8, 2011 · Viewed 10.7k times · Source

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?

Answer

wesbos picture wesbos · Sep 8, 2011

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.