Home >Web Front-end >JS Tutorial >How to Handle Right-Click Events in JavaScript?
Right Click Event Handling in JavaScript
While right-click is not a specific JavaScript event, it can be detected using existing mouse event handlers like 'mousedown', 'mouseup', or 'click'. However, these events are insufficient for identifying when the right-click menu appears.
For detecting that specific behavior, the 'oncontextmenu' event is more appropriate:
window.oncontextmenu = function() { showCustomMenu(); return false; // cancel default menu };
As for detecting the right mouse button itself, browsers provide an accessible property within the event object:
document.body.onclick = function(e) { let 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!"); };
Additional Resources:
The above is the detailed content of How to Handle Right-Click Events in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!