简体   繁体   中英

How to properly detect mouse right click?

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.

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

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM