If you want to disable the context menu using JavaScript, you can do so easily with a few lines of code:
<div class="myElement" oncontextmenu="return false;"></div>
oncontextmenu
: This event is triggered when the context menu (right-click menu) is displayed.
return false;
: This line cancels the event, preventing the menu from appearing.
Instead of using inline JavaScript, a better approach is to create a reusable class called .js-noMenu
and apply it to any element you want to prevent right clicks on. You can then include these JavaScript lines in your external script file.
[...document.querySelectorAll(".js-noMenu")].forEach( el =>
el.addEventListener('contextmenu', e => e.preventDefault())
);
<div class="js-noMenu">Try right clicking me!</div>
<p>Feel free to right click here!</p>
<p class="js-noMenu">Right click disabled here</p>
In summary, using Event.preventDefault()
helps to prevent default browser actions from taking place.