views:

121

answers:

4

What is the way to trap a right-click event on a document element? I could not find any event handlers anywhere.

+3  A: 

Right-click is special on many browsers, triggering the contextmenu event rather than a click event. Some browsers let you prevent the default behavior, some (Opera, for instance) do not. More here: http://unixpapa.com/js/mouse.html

EDIT: Rereading that page (it'd been a while), it looks like mousedown and mouseup are even more reliable than contextmenu (although all major browsers trigger contextmenu). click, on the other hand, doesn't appear to happen at all, on any significant browser.

T.J. Crowder
+3  A: 

I think there is event "oncontextmenu", you can hook it.

Here is the jQuery based contextmenu handler,

http://www.trendskitchens.co.nz/jquery/contextmenu/

PS:It doesn't work in My Opera though.

S.Mark
+2  A: 

You can use the

window.oncontextmenu

An event handler property for right-click events on the window.

If you need to disable the right click in a page then you can use something like this

window.oncontextmenu = function () {
   return false;
}

or if you need to give your own custom context menu then also you can code inside the function.

rahul
+1  A: 

You probably want the click or mousedown/up event. From quirksmode:

function doSomething(e) {
    var rightclick;
    if (!e) var e = window.event;
    if (e.which) rightclick = (e.which == 3);
    else if (e.button) rightclick = (e.button == 2);
    alert('Rightclick: ' + rightclick); // true or false
}
jonchang