How to Disable Right Click on a Website in JavaScript

08/03/2021

Contents

In this article, you will learn how to disable right click on a website in JavaScript.

Disabling right-click on a website in JavaScript

Disabling right-click on a website can help prevent unauthorized copying of images, text, and other content. In JavaScript, it can be achieved by adding an event listener to the “contextmenu” event and preventing its default behavior. Here are the steps to disable right-click on a website in JavaScript:

Add an event listener to the document object:

document.addEventListener("contextmenu", function(event){
   event.preventDefault();
});

This code will disable the right-click functionality on the entire webpage.

If you want to disable right-click functionality only on specific elements such as images, links, or paragraphs, you can add a class to those elements and modify the code accordingly.

For example, let’s say you have an image with the class “no-right-click” and you want to disable right-click only on that image:

var noRightClickImages = document.getElementsByClassName("no-right-click");

for (var i = 0; i < noRightClickImages.length; i++) {
    noRightClickImages[i].addEventListener("contextmenu", function(event){
        event.preventDefault();
    });
}

This code will disable right-click functionality only on the images with the "no-right-click" class.

You can also add a message to notify users that the right-click functionality has been disabled. For example:

document.addEventListener("contextmenu", function(event){
   event.preventDefault();
   alert("Right-click has been disabled.");
});

This code will display an alert message when users try to right-click on the webpage.

It's important to note that disabling right-click on a website is not a foolproof method for preventing unauthorized copying of content. There are other ways that users can copy content such as using the browser's "Save As" feature or taking a screenshot.