You may also see:
- Disable right click, copy, cut on web page using jQuery
Disabling Right-Click on Image
- 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
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:
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).
This was a great content indeed. It was very helpful.
Amazing! This is exactly what I was looking for.
Thanks for sharing 🙂