Is right click a Javascript event?

Javascript

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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

Solution 3 - Javascript

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

window.oncontextmenu = function () {
  alert('Right Click')
}

<h1>Please Right Click here!</h1>

Solution 4 - Javascript

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

Solution 5 - Javascript

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.

Solution 6 - Javascript

Try using which and/or button property.


function onMouseDown(e)
{
	if (e.which === 1 || e.button === 0)
	{
		console.log('Left mouse button at ' + e.clientX + 'x' + e.clientY);
	}

	if (e.which === 2 || e.button === 1)
	{
		console.log('Middle mouse button at ' + e.clientX + 'x' + e.clientY);
	}

	if (e.which === 3 || e.button === 2)
	{
		console.log('Right mouse button at ' + e.clientX + 'x' + e.clientY);
	}

	if (e.which === 4 || e.button === 3)
	{
		console.log('Backward mouse button at ' + e.clientX + 'x' + e.clientY);
	}

	if (e.which === 5 || e.button === 4)
	{
		console.log('Forward mouse button at ' + e.clientX + 'x' + e.clientY);
	}
}

window.addEventListener("mousedown", onMouseDown);

document.addEventListener("contextmenu", function(e)
{
	e.preventDefault()
});

Demo.


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)...strong text

Source: In this chapter we'll get into more details about mouse events and their properties...

Solution 7 - Javascript

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

Solution 8 - Javascript

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>

Solution 9 - Javascript

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
}

Solution 10 - Javascript

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.

Solution 11 - Javascript

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

Solution 12 - Javascript

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>

Solution 13 - Javascript

window.oncontextmenu = function (e) {
  e.preventDefault()
  alert('Right Click')
}

<h1>Please Right Click here!</h1>

Solution 14 - Javascript

Handle event using jQuery library

$(window).on("contextmenu", function(e)
{
   alert("Right click");
})

Solution 15 - Javascript

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>

Solution 16 - Javascript

This is worked with me

if (evt.xa.which == 3) 
{
    alert("Right mouse clicked");
}

Solution 17 - Javascript

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.

Solution 18 - Javascript

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>

Solution 19 - Javascript

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>

Solution 20 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBrianView Question on Stackoverflow
Solution 1 - JavascriptAndy EView Answer on Stackoverflow
Solution 2 - JavascriptPhil RykoffView Answer on Stackoverflow
Solution 3 - JavascriptRadi ChoView Answer on Stackoverflow
Solution 4 - JavascriptAlienKevinView Answer on Stackoverflow
Solution 5 - JavascriptEricView Answer on Stackoverflow
Solution 6 - JavascriptFaitherView Answer on Stackoverflow
Solution 7 - JavascriptTimothy KhouriView Answer on Stackoverflow
Solution 8 - JavascriptFrederic LeitenbergerView Answer on Stackoverflow
Solution 9 - JavascriptChickenMilkBombView Answer on Stackoverflow
Solution 10 - JavascriptphbcanadaView Answer on Stackoverflow
Solution 11 - Javascriptimal hasaranga pereraView Answer on Stackoverflow
Solution 12 - JavascriptAdnane ArView Answer on Stackoverflow
Solution 13 - JavascriptPoppyView Answer on Stackoverflow
Solution 14 - JavascriptIlyaView Answer on Stackoverflow
Solution 15 - Javascriptmadhu priyaView Answer on Stackoverflow
Solution 16 - JavascriptAmr ElngmView Answer on Stackoverflow
Solution 17 - JavascriptRobbendebieneView Answer on Stackoverflow
Solution 18 - JavascriptBaitulView Answer on Stackoverflow
Solution 19 - Javascriptcs641311View Answer on Stackoverflow
Solution 20 - JavascriptTeja KantamneniView Answer on Stackoverflow