Hiding the Menu on Right-Click with JavaScript
There are a number of reasons someone would want to disable right-clicks on their websites. Most notably, people do it to prevent users from downloading images, or copying text. Of course, if you’re reading this blog, you probably know how to work around this – there are numerous ways.
Nonetheless, let’s explore how we can accomplish this with JavaScript.
Cancelling the default menu
window.oncontextmenu = () => {
console.log("right click");
return false;
};
The oncontextmenu
event occurs when the user right-clicks on an HTML element to open the context menu. The above function is attaching the oncontextmenu
to the entire window object, thus the function will execute wherever a user right-clicks on the page.
Try it now. Copy the code above and paste it into the browser console.
You’ll notice your right-click menu is no longer in use. This is all accomplished by returning false
on the right-click event. You can swap it quickly with true
to have the menu displayed again.
We can also declare a function to accommplish the same:
function handleContextMenu(event) {
console.log("right click");
event.preventDefault();
}
window.addEventListener("contextmenu", handleContextMenu);
After defining the function, we attach an event listener to the window object.
Conclusion
In this article we looked at two seperate ways to hide the context menu on right click events.
Have you ever been on a website where you couldn’t open the menu? Did you find a workaround? Let us know in the comments below.
That wraps it up. We hope you enjoy these bite-sized articles.
Related Posts
Finding Free and Discounted Programming Books
As an avid reader, I’m always looking for places to find my next book. If they’re free, even better. Although it’s not always so easy finding them, there are plenty available online.
Read moreGetting Started with Google Cloud
In this article, we’re going to be taking a first look at Google Cloud, a leading player in the world of cloud computing, offers services and tools designed to drive innovation and ease operations.
Read moreThe Great JavaScript Debate: To Semicolon or Not?
Since I’ve started learning this language, JavaScript has undergone some heavy changes. Most notably, it seems to be the norm to not use semicolons anymore.
Read more