Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 761
jbyrd Avatar asked Sep 08 '11 04:09

jbyrd


People also ask

What is click handler in jQuery?

.click( handler )Returns: jQuery. Description: Bind an event handler to the "click". JavaScript event, or trigger that event on an element. version added: 1.0.click( handler ) handler. Type: Function( Event eventObject ) A function to execute each time the event is triggered.

How to detect element click event in JavaScript and jQuery?

Alternatively, you can use the onclick handler for specifying an event listener to receive click events. alert("Submit button is clicked!"); That’s all about detecting an element’s click event in JavaScript and jQuery.

How to handle a mouse right click event using jQuery?

To handle a mouse right click event, use the mousedown () jQuery method. Mouse left, right and middle click can also be captured using the same method. You can try to run the following code to learn how to handle a mouse right click event:

How to attach event handlers to click event of an element?

There is a shorthand method in jQuery for the .click () event to attach event handlers. alert("Submit button is clicked!"); 2. Using JavaScript With pure JavaScript, you can use the EventTarget.addEventListener () method to bind to click event of an element. alert("Submit button is clicked!");


1 Answers

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.

like image 151
wesbos Avatar answered Sep 28 '22 05:09

wesbos