Home > Web Front-end > JS Tutorial > body text

How to Handle Right-Click Events in JavaScript?

Susan Sarandon
Release: 2024-11-14 13:07:02
Original
565 people have browsed it

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

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

Additional Resources:

  • [window.oncontextmenu - MDC](https://developer.mozilla.org/en-US/docs/Web/API/Window/oncontextmenu)

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!

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