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
x
4
1
.myElement {
2
contextMenuOnRightClick: none,
3
}
4
Advertisement
Answer
The easiest way is with some very simple JavaScript:
JavaScript
1
2
1
<div class="myElement" oncontextmenu="return false;"></div>
2
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
1
3
1
[document.querySelectorAll(".js-noMenu")].forEach( el =>
2
el.addEventListener('contextmenu', e => e.preventDefault())
3
);
JavaScript
1
3
1
<div class="js-noMenu">Right click me!</div>
2
<p>You <b>can</b> contextmenu me!</p>
3
<p class="js-noMenu">You cannot here</p>
basically Event.preventDefault()
prevents the browser from triggering default actions