0

I'm trying to detect mouse right click but the following code only detects the left click.

window.oncontextmenu = function () {
    return false;
}

document.body.onclick = function (e) {
    console.log("clicked", e);
}

What is wrong with my code and how can I fix this?

I'm using the latest Chrome on macOS.

Zack Lee
  • 2,784
  • 6
  • 35
  • 77
  • Check if e.which == 3, if that's true then it's a right click. Source https://stackoverflow.com/questions/2405771/is-right-click-a-javascript-event – Ameer Aug 28 '20 at 02:32
  • @Ameer but it doesn't even print out the log on right-click before I can even check which. – Zack Lee Aug 28 '20 at 02:36
  • 1
    Because you return false from oncontextmenu. Check which button in onclick and return false there instead if it's right one – charlietfl Aug 28 '20 at 02:36
  • I don't get it. I would appreciate a full working code as an answer. – Zack Lee Aug 28 '20 at 02:38
  • on a normal modern JS note: don't use 1998 style event handlers. Use `addEventListener`, on the correct object, with the correct event name. – Mike 'Pomax' Kamermans Aug 28 '20 at 02:53

2 Answers2

3

window.oncontextmenu is already detecting mouse right click. What it does is disabling the default browser right click context menu for now, but you can add any additional code above it to trigger whenever right click event is performed.

window.oncontextmenu = function () {
  console.log("right clicked");
    return false;
}

You can try by running the code snippet and right clicking the empty space. Left clicking will not print the console.log.

EDIT: As mentioned in the comments, you could also use addEventListener to listen to contextmenu.

window.addEventListener('contextmenu', function(ev) {
  ev.preventDefault();
  console.log("right clicked");
});
Alfred
  • 644
  • 4
  • 12
1

You Can Use This Function to get right & left click event But You Have To Use onmousedown instead using onclick

function myFunction() {
var rightclick;
if (!e) var e = window.event;
if (e.which) rightclick = (e.which == 3);
else if (e.button) rightclick = (e.button == 2);
isRclick =  rightclick; // true or false


alert(isRclick);

}

BugsCreator
  • 433
  • 3
  • 10