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
The 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 moreHacktoberfest 2024: Get a Free JavaScript Today Sticker
October is here, and that means one thing in the tech world—Hacktoberfest! This annual event, powered by DigitalOcean, Cloudflare, Quira, and other sponsors, encourages developers of all skill levels to contribute to open-source projects.
Read moreCreating a Real Time Chat Application with React, Node, and TailwindCSS
In this tutorial, we will show you how to build a real-time chat application using React and Vite,as well as a simple Node backend.
Read more