When a user on your website or app right-clicks, the contextmenu event is triggered.
We can listen for this event by attaching an event listener to the window interface, but I'd suggest first adding the below one-liner to ensure compatibility with some older browsers:
typeof window.addEventListener === `undefined` && (window.addEventListener = (e, cb) => window.attachEvent(`on${e}`, cb));
Anyway, here is the actual snippet that will listen for the contextmenu
event, intercept it, and prevent the default behavior:
window.addEventListener(`contextmenu`, (e) => {
e.preventDefault();
});
Here is a one-liner variant that is equivalent to the above snippet:
window.addEventListener(`contextmenu`, (e) => e.preventDefault());
Conclusion
While exploring how you can create custom context menus is a bit beyond the scope of this article, I hope you found this snippet useful.
Remember to only disable context menus when absolutely necessary!
Top comments (0)