Is right click a Javascript event? If so, how do I use it?
As others have mentioned, the right mouse button can be detected through the usual mouse events (mousedown, mouseup, click). However, if you're looking for a firing event when the right-click menu is brought up, you're looking in the wrong place. The right-click/context menu is also accessible via the keyboard (shift+F10 or context menu key on Windows and some Linux). In this situation, the event that you're looking for is oncontextmenu
:
window.oncontextmenu = function ()
{
showCustomMenu();
return false; // cancel default menu
}
As for the mouse events themselves, browsers set a property to the event object that is accessible from the event handling function:
document.body.onclick = function (e) {
var isRightMB;
e = e || window.event;
if ("which" in e) // Gecko (Firefox), WebKit (Safari/Chrome) & Opera
isRightMB = e.which == 3;
else if ("button" in e) // IE, Opera
isRightMB = e.button == 2;
alert("Right mouse button " + (isRightMB ? "" : " was not") + "clicked!");
}
onmousedown
and onmouseup
, but not onclick
. Apparently, in Chrome, onclick
is only triggered for the left-mouse-button. (and yes guys, I tested this multiple times) For detecting a right-mouse-click, you have to either combine onmousedown
and onmouseup
, or use oncontextmenu
. –
Interclavicle have a look at the following jQuery code:
$("#myId").mousedown(function(ev){
if(ev.which == 3)
{
alert("Right mouse button clicked on element with id myId");
}
});
The value of which
will be:
- 1 for the left button
- 2 for the middle button
- 3 for the right button
.which
not the same as .button
? O.o .button
=> 0,1,2; which
=> 1,2,3. that is just wrong. –
Bluing You could use the event window.oncontextmenu
, for example:
window.oncontextmenu = function () {
alert('Right Click')
}
<h1>Please Right Click here!</h1>
window.oncontextmenu = function () { e.preventDefault() }
didn't work. –
Ontario You might want to try the following properties:
function onMouseDown(e)
{
if (e.which === 1 || e.button === 0)
{
console.log('"Left" at ' + e.clientX + 'x' + e.clientY);
}
if (e.which === 2 || e.button === 1)
{
console.log('"Middle" at ' + e.clientX + 'x' + e.clientY);
}
if (e.which === 3 || e.button === 2)
{
console.log('"Right" at ' + e.clientX + 'x' + e.clientY);
}
if (e.which === 4 || e.button === 3)
{
console.log('"Back" at ' + e.clientX + 'x' + e.clientY);
}
if (e.which === 5 || e.button === 4)
{
console.log('"Forward" at ' + e.clientX + 'x' + e.clientY);
}
}
window.addEventListener('mousedown', onMouseDown);
document.addEventListener('contextmenu', e => e?.cancelable && e.preventDefault());
"How To Keep People From Pushing Your Buttons" by Albert Ellis
MacOS
On Windows and Linux there are modifier keys Alt, Shift and Ctrl. On Mac there’s one more: Cmd, corresponding to the property
metaKey
...
Even if we’d like to force Mac users to Ctrl+click
– that’s kind of difficult. The problem is: aleft-click
with Ctrl is interpreted as aright-click
on MacOS, and it generates thecontextmenu
event, notclick
like Windows/Linux.
So if we want users of all operating systems to feel comfortable, then together withctrlKey
we should checkmetaKey
.
For JS-code it means that we should checkif (event.ctrlKey || event.metaKey)
...
Source: In this chapter we'll get into more details about mouse events and their properties...
Source: https://amazon.com/dp/B07DZWLPG9
Related: "cancelable" read-only property of the Event interface...
If you want to detect right mouse click, you shouldn't use MouseEvent.which
property as it is non-standard and there's large incompatibility among browsers. (see MDN) You should instead use MouseEvent.button
. It returns a number representing a given button:
0
: Main button pressed, usually the left button or the un-initialized state1
: Auxiliary button pressed, usually the wheel button or the middle button (if present)2
: Secondary button pressed, usually the right button3
: Fourth button, typically the Browser Back button4
: Fifth button, typically the Browser Forward button
MouseEvent.button
handles more input types than just standard mouse:
Buttons may be configured differently to the standard "left to right" layout. A mouse configured for left-handed use may have the button actions reversed. Some pointing devices only have one button and use keyboard or other input mechanisms to indicate main, secondary, auxilary, etc. Others may have many buttons mapped to different functions and button values.
Reference:
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.
Thus, you can regard "onContextMenu" as the right click event. It's an HTML5.0 standard.
No, but you can detect what mouse button was used in the "onmousedown" event... and from there determine if it was a "right-click".
onmousedown
, onmouseup
and onclick
. If you're looking at overriding the right-click menu, however, these events are not what you should be using (see my answer below). –
Tibia Add an e.preventDefault to stop the menu from coming up(in case you don't want it)
window.oncontextmenu = function(e) {
e.preventDefault();
alert('You Clicked');
}
<h1>Right Click</h1>
Yes - it is!
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
}
elem.addEventListener("click", doSomething)
–
Cretonne window.oncontextmenu = function (e) {
e.preventDefault()
alert('Right Click')
}
<h1>Please Right Click here!</h1>
Yes, oncontextmenu is probably the best alternative but be aware that it triggers on mouse down whereas click will trigger on mouse up.
Other related questions were asking about double right click - which apparently isn't supported except through manual timer checking. One reason you might want to be able to have right double click is if you need/want to support left-handed mouse input (button reversal). The browser implementations seem to make a lot of assumptions about how we should be using the available input devices.
The following code is using jQuery to generate a custom rightclick
event based on the default mousedown
and mouseup
events.
It considers the following points:
- trigger on mouseup
- trigger only when pressed mousedown on the same element before
- this code especially also works in JFX Webview (since the
contextmenu
event is not triggered there) - it does NOT trigger when the contextmenu key on the keyboard is pressed (like the solution with the
on('contextmenu', ...)
does
$(function ()
{ // global rightclick handler - trigger custom event "rightclick"
var mouseDownElements = [];
$(document).on('mousedown', '*', function(event)
{
if (event.which == 3)
{
mouseDownElements.push(this);
}
});
$(document).on('mouseup', '*', function(event)
{
if (event.which == 3 && mouseDownElements.indexOf(this) >= 0)
{
$(this).trigger('rightclick');
}
});
$(document).on('mouseup', function()
{
mouseDownElements.length = 0;
});
// disable contextmenu
$(document).on('contextmenu', function(event)
{
event.preventDefault();
});
});
// Usage:
$('#testButton').on('rightclick', function(event)
{
alert('this was a rightclick');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="testButton">Rightclick me</button>
Easiest way to get right click done is using
$('classx').on('contextmenu', function (event) {
});
However this is not cross browser solution, browsers behave differently for this event especially firefox and IE. I would recommend below for a cross browser solution
$('classx').on('mousedown', function (event) {
var keycode = ( event.keyCode ? event.keyCode : event.which );
if (keycode === 3) {
//your right click code goes here
}
});
That is the easiest way to fire it, and it works on all browsers except application webviews like ( CefSharp Chromium etc ... ). I hope my code will help you and good luck!
const contentToRightClick=document.querySelector("div#contentToRightClick");
//const contentToRightClick=window; //If you want to add it into the whole document
contentToRightClick.oncontextmenu=function(e){
e=(e||window.event);
e.preventDefault();
console.log(e);
return false; //Remove it if you want to keep the default contextmenu
}
div#contentToRightClick{
background-color: #eee;
border: 1px solid rgba(0,0,0,.2);
overflow: hidden;
padding: 20px;
height: 150px;
}
<div id="contentToRightClick">Right click on the box !</div>
Most of the given solutions using the mouseup
or contextmenu
events fire every time the right mouse button goes up, but they don't check wether it was down before.
If you are looking for a true right click event, which only fires when the mouse button has been pressed and released within the same element, then you should use the auxclick
event. Since this fires for every none-primary mouse button you should also filter other events by checking the button
property.
window.addEventListener("auxclick", (event) => {
if (event.button === 2) alert("Right click");
});
You can also create your own right click event by adding the following code to the start of your JavaScript:
{
const rightClickEvent = new CustomEvent('rightclick', { bubbles: true });
window.addEventListener("auxclick", (event) => {
if (event.button === 2) {
event.target.dispatchEvent(rightClickEvent);
}
});
}
You can then listen for right click events via the addEventListener
method like so:
your_element.addEventListener("rightclick", your_function);
Read more about the auxclick
event on MDN.
Handle event using jQuery
library
$(window).on("contextmenu", function(e)
{
alert("Right click");
})
If You want to call the function while right click event means we can use following
<html lang="en" oncontextmenu="func(); return false;">
</html>
<script>
function func(){
alert("Yes");
}
</script>
This is worked with me
if (evt.xa.which == 3)
{
alert("Right mouse clicked");
}
Yes, It's a Javascript event, you can test it with below code.
<div id="contextArea">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</div>
<script>
var contextarea = $("#contextArea");
contextarea.contextmenu(function (e) {
e.preventDefault();
console.log("right click from p tag");
})
</script>
For track right click
window.oncontextmenu = () =>{
console.log("Right click")
}
Only for right click
In JQuery you can detect it using the following codes:
$('.target').on('contextmenu', function (evt) {
evt.preventDefault();
});
$('.target').mouseup(function (evt) {
if (evt.which === 3) { // right-click
$(this).css("background-color","blue");
$(this).text("RIGHT");
}
else if (evt.which === 1) {
$(this).css("background-color","red");
$(this).text("LEFT");
}
});
.target {
display: inline-block;
height: 100px;
width: 100px;
background: gray;
text-align: center;
color: white;
font-size: 25px;
vertical-align: middle;
margin: 25px;
}
.container {
width: 100%;
height: 140px;
background: #AAA;
vertical-align: middle;
text-align: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="target" id="target">Click</div>
<div class="target" id="target">Right</div>
<div class="target" id="target">Click me!</div>
</div>
Yes, its a javascript mousedown event. There is a jQuery plugin too to do it
© 2022 - 2024 — McMap. All rights reserved.