How can I capture the right-click event in JavaScript?

Giffyguy picture Giffyguy · Nov 20, 2010 · Viewed 304.3k times · Source

I want to block the standard context menus, and handle the right-click event manually.

How is this done?

Answer

Chase picture Chase · Nov 21, 2010

Use the oncontextmenu event.

Here's an example:

<div oncontextmenu="javascript:alert('success!');return false;">
    Lorem Ipsum
</div>

And using event listeners (credit to rampion from a comment in 2011):

el.addEventListener('contextmenu', function(ev) {
    ev.preventDefault();
    alert('success!');
    return false;
}, false);

Don't forget to return false, otherwise the standard context menu will still pop up.

If you are going to use a function you've written rather than javascript:alert("Success!"), remember to return false in BOTH the function AND the oncontextmenu attribute.