Home >Web Front-end >JS Tutorial >How to Handle Right-Click Events in JavaScript?

How to Handle Right-Click Events in JavaScript?

Susan Sarandon
Susan SarandonOriginal
2024-11-14 13:07:02654browse

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:

  • [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!

Statement:
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