How can I trigger some action with right click after disabling the browser context menu ?
I tried this . . .
$(document).ready(function(){ $(document).bind("contextmenu",function(e){ $('.alert').fadeToggle(); return false; }); });
We will use the oncontextmenu property to listen to the right-click events. We will create a rightClick() function. In this function, we will call the preventDefault() method of the mouse click event which will cancel the default behavior of the right-click event. We can also return “false” to cancel the event.
To capture the right-click event in JavaScript, we can listen for the contextmenu event. el. addEventListener( "contextmenu", (ev) => { ev. preventDefault(); //... }, false );
oncontextmenu = function() {return false;}; $(document). mousedown(function(e){ if( e. button == 2 ) { alert('Right mouse button! '); return false; } return true; }); });
Purpose. The event binding allows you to add an event handler for a specified event so that your chosen JavaScript function will be invoked when that event is triggered for the associated DOM element. This can be used to bind to any event, such as keypress , mouseover or mouseout .
There is no built-in oncontextmenu event handler in jQuery, but you can do something like this:
$(document).ready(function(){ document.oncontextmenu = function() {return false;}; $(document).mousedown(function(e){ if( e.button == 2 ) { alert('Right mouse button!'); return false; } return true; }); });
Basically I cancel the oncontextmenu event of the DOM element to disable the browser context menu, and then I capture the mousedown event with jQuery, and there you can know in the event argument which button has been pressed.
You can try the above example here.
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