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:

JavaScript

Advertisement

Answer

The easiest way is with some very simple JavaScript:

JavaScript
  • 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.

JavaScript
JavaScript

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

Advertisement