Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

How is this done?

like image 967
Giffyguy Avatar asked Sep 28 '22 18:09

Giffyguy


People also ask

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 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.

What is Oncontextmenu in JavaScript?

The oncontextmenu attribute fires when the user right-clicks on an element to open the context menu. Note: Although the oncontextmenu event is supported in all browsers, the contextmenu attribute is currently only supported in Firefox.

How does HTML detect right click?

Ya, though w3c says the right click can be detected by the click event, onClick is not triggered through right click in usual browsers. In fact, right click only trigger onMouseDown onMouseUp and onContextMenu.


2 Answers

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.

like image 435
Chase Finch Avatar answered Oct 19 '22 01:10

Chase Finch


I think that you are looking for something like this:

   function rightclick() {
    var rightclick;
    var e = window.event;
    if (e.which) rightclick = (e.which == 3);
    else if (e.button) rightclick = (e.button == 2);
    alert(rightclick); // true or false, you can trap right click here by if comparison
}

(http://www.quirksmode.org/js/events_properties.html)

And then use the onmousedown even with the function rightclick() (if you want to use it globally on whole page you can do this <body onmousedown=rightclick(); >

like image 43
cyber-guard Avatar answered Oct 19 '22 03:10

cyber-guard