How do you obtain the clicked mouse button using jQuery?
$('div').bind('click', function(){ alert('clicked'); });
this is triggered by both right and left click, what is the way of being able to catch right mouse click? I'd be happy if something like below exists:
$('div').bind('rightclick', function(){ alert('right mouse button is pressed'); });
oncontextmenu = function() {return false;}; $(document). mousedown(function(e){ if( e. button == 2 ) { alert('Right mouse button! '); return false; } return true; }); });
When you press the one on the right, it is called a right click. By default, the left button is the main mouse button, and is used for common tasks such as selecting objects and double-clicking. The right mouse button is often used to open contextual menus, which are pop-up menus that change depending where you click.
jQuery click() MethodThe click event occurs when an element is clicked. The click() method triggers the click event, or attaches a function to run when a click event occurs.
Events order For instance, a left-button click first triggers mousedown , when the button is pressed, then mouseup and click when it's released. In cases when a single action initiates multiple events, their order is fixed. That is, the handlers are called in the order mousedown → mouseup → click .
As of jQuery version 1.1.3, event.which
normalizes event.keyCode
and event.charCode
so you don't have to worry about browser compatibility issues. Documentation on event.which
event.which
will give 1, 2 or 3 for left, middle and right mouse buttons respectively so:
$('#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!'); } });
Edit: I changed it to work for dynamically added elements using .on()
in jQuery 1.7 or above:
$(document).on("contextmenu", ".element", function(e){ alert('Context Menu event has fired!'); return false; });
Demo: jsfiddle.net/Kn9s7/5
[Start of original post] This is what worked for me:
$('.element').bind("contextmenu",function(e){ alert('Context Menu event has fired!'); return false; });
In case you are into multiple solutions ^^
Edit: Tim Down brings up a good point that it's not always going to be a right-click
that fires the contextmenu
event, but also when the context menu key is pressed (which is arguably a replacement for a right-click
)
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