Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind event to right mouse click

Tags:

jquery

css

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;     }); }); 
like image 623
Zac Avatar asked Apr 01 '09 17:04

Zac


People also ask

How do I add a right click event?

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.

How can I capture the right click event in JavaScript?

To capture the right-click event in JavaScript, we can listen for the contextmenu event. el. addEventListener( "contextmenu", (ev) => { ev. preventDefault(); //... }, false );

How does jQuery detect right click?

oncontextmenu = function() {return false;}; $(document). mousedown(function(e){ if( e. button == 2 ) { alert('Right mouse button! '); return false; } return true; }); });

What is bind event in JavaScript?

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 .


1 Answers

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.

like image 73
Christian C. Salvadó Avatar answered Oct 27 '22 01:10

Christian C. Salvadó