How to The event occurs when the user right-clicks on an element to open a context menu in JavaScript ?


In JavaScript, the event that occurs when the user right-clicks on an element to open a context menu is called the contextmenu event.

There are multiple ways to add an event listener for the contextmenu event:

  • Using the addEventListener() method:
const element = document.getElementById("myElement");

element.addEventListener("contextmenu", function(event) {
  // code to be executed when the contextmenu event occurs
  event.preventDefault(); // to prevent the default context menu from appearing
});
  • Using the oncontextmenu property:
const element = document.getElementById("myElement");

element.oncontextmenu = function(event) {
  // code to be executed when the contextmenu event occurs
  event.preventDefault(); // to prevent the default context menu from appearing
};

In both examples, the event.preventDefault() method is used to prevent the default context menu from appearing. This is useful if you want to create a custom context menu using HTML and CSS.

Here's a complete example that demonstrates how to create a custom context menu using HTML and CSS:

<!DOCTYPE html>
<html>
<head>
  <style>
    .context-menu {
      display: none;
      position: absolute;
      background-color: #fff;
      border: 1px solid #ccc;
      padding: 5px;
    }
  </style>
</head>
<body>
  <div id="myElement">Right-click me</div>

  <div class="context-menu" id="myContextMenu">
    <ul>
      <li>Option 1</li>
      <li>Option 2</li>
      <li>Option 3</li>
    </ul>
  </div>

  <script>
    const element = document.getElementById("myElement");
    const contextMenu = document.getElementById("myContextMenu");

    element.addEventListener("contextmenu", function(event) {
      event.preventDefault();

      // show the custom context menu
      contextMenu.style.display = "block";
      contextMenu.style.left = event.pageX + "px";
      contextMenu.style.top = event.pageY + "px";
    });

    document.addEventListener("click", function(event) {
      // hide the custom context menu when the user clicks outside of it
      if (event.target != contextMenu) {
        contextMenu.style.display = "none";
      }
    });
  </script>
</body>
</html>

In this example, we first define a custom context menu using HTML and CSS. We then add an event listener for the contextmenu event on the myElement div. When the event occurs, we prevent the default context menu from appearing and show the custom context menu at the position of the mouse cursor. Finally, we add a click event listener to the document to hide the custom context menu when the user clicks outside of it.



About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.