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.

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.

comments powered by Disqus

Related Posts

The Best Way to Learn How to Code in 2024

Codecademy has been around for awhile now, but we felt this masterful site deserved to be highlighted in an article. It is one of the resources I originally used when I was learning how to code.

Read more

Unveiling the Fascination of the Collatz Conjecture: Exploring Sequence Creation with JavaScript

The Collatz Conjecture, also known as the 3x+1 problem, is a fascinating mathematical puzzle that has intrigued mathematicians for decades. It has sparked publications with titles such as The Simplest Math Problem Could Be Unsolvable, or The Simple Math Problem We Still Can’t Solve because it is, indeed, rather simple-looking.

Read more

The Art of Data Visualization: Exploring D3.js

Data is everywhere, flowing into our applications from various sources at an unprecedented rate. However, raw data alone holds little value unless it can be transformed into meaningful insights.

Read more