When we right-click a page within a web page, the browser displays the default context menu. This article shows you how to replace the default context menu with our custom menu, allowing you to perform some custom actions.

We start by creating an element that we want to display a custom context menu.

<div id="element">Right click on the</div>
<div id="menu">I am a menu</div>
Copy the code

Prevents the default context menu from being displayed

To do this, simply block the default behavior within the ContextMenu event.

const el = document.getElementById('element');

el.addEventListener('contextmenu'.function (e) {
  e.preventDefault();
});
Copy the code

Displays a custom menu at the click location

The location of the customized menu must be calculated. Before calculation, locate the menu in a container. Therefore, we need to wrap Element and Menu.

<div id="relative">
  <div id="element"></div>
  <! -- Menus are hidden by default -->
  <div id="menu hidden"></div>
</div>
Copy the code
.relative {
  position: relative;
}

.absolute {
  position: absolute;
}

.hidden {
  display: none;
}
Copy the code

Next, we can calculate the positioning of the custom menu. We need to get mouse position information and Element container size information.

el.addEventListener('contextmenu'.function (e) {
  const rect = el.getBoundingClientRect();

  const x = e.clientX - rect.left;
  const y = e.clientY - rect.top;

  // Set the location of the menu
  menu.style.left = `${x}px`;
  menu.style.top = `${y}px`;

  // Display the menu
  menu.classList.remove('hidden');
});
Copy the code

Hide menu when you click on the outer menu area

el.addEventListener('contextmenu'.function (e) {
  // ...
  document.addEventListener('click', handleClickDocument);
});

function handleClickDocument(e) {
  constisClickedOutside = ! menu.contains(e.target);if (isClickedOutside) {
    // Hide the menu
    menu.classList.add('hidden');

    // Remove the event
    document.removeEventListener('click', handleClickDocument); }}Copy the code

Add Hidden Class to menu to hide menu. When you hide the menu, you also need to remove the Click event on the document, which means that the click event is executed only once.

There is another way to make the event execute once, passing a third parameter {once: true} to the addEventListener method.

document.addEventListener('click', handleClickDocument, { once: true });
Copy the code