Hiding the Menu on Right-Click with JavaScript
Javascript Tutorial

Hiding the Menu on Right-Click with JavaScript

1 min read

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.

{{< image title=“” w=“” h=“” o=“webp q100” p=“center” c=“rounded” src=“images/oncontextmenu.png” alt=“Browser Console for Code” >}}

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.

About the Author

Matt Fay

Matt Fay

Matt is the founder of JavaScript Today, a platform dedicated to high-quality JavaScript education and commentary. With a deep curiosity for technology, he gravitates toward understanding how things work and has been diving into the world of information security. Outside of coding, Matt enjoys exploring languages; he can understand some Russian and Italian, and is currently learning Thai.

Discussion (Loading...)

Join the conversation

Join the Discussion

Sign in to share your thoughts and engage with the JavaScript Today community.

Loading comments...

Related Articles

Continue your learning journey with these related posts

Never Miss a JavaScript Update

Join our community of developers and receive insightful articles and coding tips every week.