Is right click a Javascript event?
Asked Answered
G

22

235

Is right click a Javascript event? If so, how do I use it?

Gemina answered 9/3, 2010 at 0:19 Comment(0)
T
249

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!");
} 

window.oncontextmenu - MDC

Tibia answered 9/3, 2010 at 0:30 Comment(3)
Just like with the which/button issue, the 'oncontextmenu' is not implemented the same in all browsers... see quirksmode.org/dom/events/contextmenu.html for some of the 'gotchas'.Pilocarpine
Keep in mind that on Mac FF ctrl+rightclick will come through as a left mouse click (e.which === 1), while on Mac Chrome ctrl+rightclick will come through as the expected right mouse click (e.ctrlKey && e.which === 3).Vacillate
In Chrome 59, the right-mouse-button triggers 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
D
39

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
Demure answered 9/3, 2010 at 0:34 Comment(2)
Eeeew, that's terrible! Why is .which not the same as .button? O.o .button => 0,1,2; which => 1,2,3. that is just wrong.Bluing
It is deprecated.Cider
F
20

You could use the event window.oncontextmenu, for example:

window.oncontextmenu = function () {
  alert('Right Click')
}
<h1>Please Right Click here!</h1>
Footy answered 27/9, 2015 at 17:1 Comment(5)
this also fires left mbApish
Awesome +1, now how do I block the context menu? @user12345678Ontario
@Ontario e.preventDefault()Chilt
@BrianAllanWest Is that jQuery? I don't know how to use that. window.oncontextmenu = function () { e.preventDefault() } didn't work.Ontario
@Shayan, no it's raw javascript... you would use it like this... window.oncontextmenu = function(e) { e.preventDefault();} this prevents the default behavior of the browser when the context menu (ie: right mouse click or hold on mac) is pressed.Chilt
L
18

You might want to try the following properties:

  1. button - (caniuse);
  2. which - (caniuse) (deprecated).

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: a left-click with Ctrl is interpreted as a right-click on MacOS, and it generates the contextmenu event, not click like Windows/Linux.
So if we want users of all operating systems to feel comfortable, then together with ctrlKey we should check metaKey.
For JS-code it means that we should check if (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...

Lynettalynette answered 28/6, 2020 at 0:11 Comment(2)
doesn't work for mac.. On mac, right click is control + clickParticolored
@LeoCavalcante Thank you ^^ Added information about MacOS from the resource.Lynettalynette
H
13

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 state
  • 1: Auxiliary button pressed, usually the wheel button or the middle button (if present)
  • 2: Secondary button pressed, usually the right button
  • 3: Fourth button, typically the Browser Back button
  • 4: 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:

  1. https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/which
  2. https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button
Herald answered 3/2, 2019 at 11:16 Comment(0)
B
9

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.

Berberine answered 15/1, 2013 at 3:27 Comment(1)
Yes, sounds like a great solution, especially if you are targeting newer browsers. I don't think this is an HTML5.0 only, because even IE 5.5 supports it on elements! Here's more on which browsers support it: quirksmode.org/dom/events/contextmenu.htmlBifilar
F
4

No, but you can detect what mouse button was used in the "onmousedown" event... and from there determine if it was a "right-click".

Foray answered 9/3, 2010 at 0:23 Comment(1)
@Brian: a right click will trigger 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
D
4

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>
Ditch answered 27/1, 2022 at 13:34 Comment(0)
W
3

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
}
Winfordwinfred answered 9/3, 2010 at 0:22 Comment(2)
Well - technically its not an "event" but it can be used.Winfordwinfred
@TimothyKhouri (and anyone else here): this is a compatible event listener function. You would pass the function object itself as the second argument to addEventListener, which would then call it on the occurrence of the specified event. For example: elem.addEventListener("click", doSomething)Cretonne
A
3

window.oncontextmenu = function (e) {
  e.preventDefault()
  alert('Right Click')
}
<h1>Please Right Click here!</h1>
Accommodative answered 8/11, 2019 at 4:3 Comment(0)
W
2

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.

Wroughtup answered 25/6, 2014 at 17:48 Comment(0)
Y
2

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>
Yestreen answered 11/12, 2015 at 12:4 Comment(0)
S
1

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      
    }
});
Surra answered 17/4, 2017 at 12:56 Comment(0)
M
1

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>
Maomaoism answered 26/8, 2019 at 22:11 Comment(0)
R
1

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.

Relieve answered 16/2, 2021 at 14:21 Comment(1)
Doesn't work on Mac.Brag
P
0

Handle event using jQuery library

$(window).on("contextmenu", function(e)
{
   alert("Right click");
})
Palaeozoic answered 6/6, 2014 at 15:54 Comment(0)
M
0

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>
Mackoff answered 15/2, 2016 at 12:19 Comment(0)
D
0

This is worked with me

if (evt.xa.which == 3) 
{
    alert("Right mouse clicked");
}
Droop answered 1/12, 2018 at 15:37 Comment(0)
F
0

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>
Foxy answered 22/11, 2021 at 18:51 Comment(0)
C
0
For track right click 

window.oncontextmenu = () =>{

console.log("Right click")

}

Only for right click

Clause answered 30/9, 2022 at 6:56 Comment(0)
M
0

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>
Mcmorris answered 1/12, 2022 at 20:21 Comment(0)
W
-2

Yes, its a javascript mousedown event. There is a jQuery plugin too to do it

Wellspoken answered 9/3, 2010 at 0:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.