How to disable right click on Image in JavaScript

In this tutorial, we will learn about how to disable right-click on Images in JavaScript.Disabling right-click on images can help you to keep your image protected by preventing easy download of the image.

You may also see:

Disabling Right-Click on Image

Javascript provides various functions and methods to disable right-click on images. We will learn using two commonly used methods:

  • Using bind() method
  • Using addEventListener() method

Function bind() Method

Bind() function is used to create a new function. A function has its own keyword which is set to the provided value, with a given sequence of arguments.

Syntax of the function bind() method is as follows:

function.bind(thisArg [, arg1[, arg2[, ...]]]

This is a very easy method to implement. Just add the script in your head tag to use.

How to disable right click on Image in JavaScript

In this code, I have used an image already present on my desktop. Here we have called the function bind() method. The function returns a False statement to disable the right-click.

By Function addEventListener() Method

addEventListener() is an inbuilt javascript method that is used the handle any events that occur on a webpage. It takes two arguments :
i) Event:  it needs to wait to occur.
ii) Listener: Function to be triggered when the event occurs.

Syntax of the function addEventListener() method is as follows:

element.addEventListener(event, listener);

Implementation of the method goes as follows:

addEventListener() Method

Here in the given code, I have passed ‘contextmenu’ as my event parameter and I have called ‘function(e)‘ as my listener parameter.
[NOTE: Here, ‘e’ is name of variable used. You can use any other name also instead of ‘e’. Just make sure it is not an inbuilt keyword].
Whenever a user tries to right-click on the image (i.e Event Occurs), function(e) is called which in turn calls the inbuilt function preventDefault() which prevents the default event to occur(here right-click is prevented).

Also read: Null vs Undefined in JavaScript

One response to “How to disable right click on Image in JavaScript”

  1. Pranavi says:

    This was a great content indeed. It was very helpful.

Leave a Reply

Your email address will not be published. Required fields are marked *