JavaScript Right-Click Event
Is it possible to detect right-clicks in JavaScript? Yes, you can use JavaScript mouse events like 'mousedown' or 'mouseup' to detect right-clicks. However, if you're aiming to track the opening of the right-click menu, you'll need to use 'oncontextmenu' instead.
Detecting Right-Click with mouse Events
To detect right-clicks using mouse events, check the 'event' object's 'which' or 'button' properties within 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!"); }
oncontextmenu Event for Right-Click Menu
The 'oncontextmenu' event triggers when the right-click menu opens, regardless of whether the mouse or keyboard was used. To use this event, simply assign a function as its handler:
window.oncontextmenu = function () { showCustomMenu(); return false; // cancel default menu }
By combining 'mouse' events and 'oncontextmenu', you can effectively handle right-click interactions in JavaScript.
The above is the detailed content of How to Detect Right-Clicks in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!