Home > Web Front-end > JS Tutorial > How to Detect Right-Clicks in JavaScript?

How to Detect Right-Clicks in JavaScript?

Susan Sarandon
Release: 2024-11-10 13:40:02
Original
309 people have browsed it

How to Detect Right-Clicks in JavaScript?

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!");
} 
Copy after login

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
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template