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:
- Disable right click, copy, cut on web page using jQuery
- Disable HTML button after clicking on it in JavaScript
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.
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:
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
This was a great content indeed. It was very helpful.
Amazing! This is exactly what I was looking for.
Thanks for sharing 🙂