Skip to content
Advertisement

Prevent context menu from opening on a right click over element

I want my website to have a custom interaction when the user right clicks on an element, <div class="myElement"></div>. Thus, I don’t what the context menu to also pop up when the element is right clicked as to not spoil the UX. Is there a way to do this (preferably in CSS, but vanilla js works too)?

Desired:

.myElement {
    contextMenuOnRightClick: none,
}

Advertisement

Answer

The easiest way is with some very simple JavaScript:

<div class="myElement" oncontextmenu="return false;"></div>
  • oncontextmenu: event fires when the context menu (right-click menu) is shown.
  • return false;: cancels the event; which stops the menu from showing.

Yet better, instead of using inline JS, create a reusable className .js-noMenu and add it to any element that should prevent right clicks.
Place the JS lines into your Javascript file.

[...document.querySelectorAll(".js-noMenu")].forEach( el => 
 el.addEventListener('contextmenu', e => e.preventDefault())
);
<div class="js-noMenu">Right click me!</div>
<p>You <b>can</b> contextmenu me!</p>
<p class="js-noMenu">You cannot here</p>

basically Event.preventDefault() prevents the browser from triggering default actions

Advertisement