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?
.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.
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.
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:
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!");
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With