Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript
communitycreator

How to disable the right-click menu in JavaScript

Programming Bytes

Overview

We can disable the right-click menu on the web page by preventing the default behavior when the right-click event happens. The contextmenu event will be fired when user right-clicks on a div. We can bind an event listener for that event and prevent the default behavior.

Code

The below code demonstrates how to disable right-click.

Console
Disabling the right-click

Explanation

Lines 5-10: We create two div here. One div with the ID no_right_click in which the right-click will be disabled and the other div will have the normal characteristics.

Line 13: We use the getElementById method to get the reference for the element with the ID no_right_click and stored that element in a variable ele.

Lines 14-17: For the ele, we add an event listener for the contextmenu event. Inside the event listener, we prevent the default browser behavior by calling the ev.preventDefault() method. This will prevent the browser from displaying the right-click menu.

RELATED TAGS

javascript
communitycreator
RELATED COURSES

View all Courses

Keep Exploring