How To Disable Right Click With JavaScript
In certain situations it might be useful to disable the browser right click context menu functionality. In this article I’ll quickly show you how it’s done. As the context menu is an important user interaction pattern we of course shouldn’t disable it lightly, let’s take a look.
In my case I wanted to disable the right click interaction because it creates very strange situations when users drag an item and then accidentally click the right mouse button. Events fail to fire, or fire in another order, items get stuck, etc.
However the context menu triggered by the right click contains important functionality for the user (searching, printing, translating), so it’s smart to only disable it temporarily. In my case I only disable it when the user starts dragging an item.
Please note that at this time the "contextmenu" event doesn’t fire on iOS Safari
The code below will disable the context menu in all situations.
<script>
document.addEventListener('contextmenu', (e) => {
e.preventDefault();
});
</script>
To only disable it in certain situations we can do with a basic if statement.
document.addEventListener('contextmenu', (e) => {
// only disable the context menu when the user is doing something
if (!userIsDoingSomething) {
return;
}
e.preventDefault();
});
Alternatively we can add and remove the contextmenu event depending on if the user started a certain activity.
function preventContextMenu(e) {
e.preventDefault();
}
// user started doing something, let's disable the context menu
function userStartsDoingSomething() {
document.addEventListener('contextmenu', preventContextMenu);
}
// user stopped doing something, let's enable the context menu
function userStopsDoingSomething() {
document.removeEventListener('contextmenu', preventContextMenu);
}
Performance wise there’s not much difference between these solutions. However it’s a bit more clean to only listen for the contextmenu event when it’s relevant, instead of always listening and checking if we should prevent the menu every time the right mouse button is pressed.
To disable right click on a selection of elements we can use the code below, in this case the event handler is attached to an element and the event will be prevented on the element and all its children.
<p id="my-element">Right click doesn't work here.</p>
<script>
// Select the element
const myElement = document.querySelector('#my-element');
// Listen for the `contextmenu` event
myElement.addEventListener('contextmenu', (e) => {
e.preventDefault();
});
</script>
Let’s see that in action.
Alright, that’s all there is to it, now you know how it’s done. Great power, great responsibility, please use it wisely.