Using jQuery and JavaScript, you can manage actions like right-clicking, cutting, copying, and pasting across a webpage or in specific sections.
This is often used in online tests where students shouldn’t be able to copy and paste text.
You can also create your own custom context menu to show up when someone right-clicks.
Table of Content
- Disable Right click from the whole document using jQuery
- Disable Right click from a particular element using jQuery
- Disable cut, copy, and paste using jQuery
- Conclusion
1. Disable Right click from the whole document using jQuery
Bind contextmenu
event on the document
and return false when that event triggers.
In this example, I use the setTimeout()
function to show an error message when someone right-clicks on the document.
You can either use
return false
ore.preventDefault()
to disable the Right click. I usedreturn false
in the example.
$(document).bind('contextmenu', function (e) { $("#error").fadeIn("slow"); setTimeout(function(){ $("#error").fadeOut("slow"); },2000); return false; });
With JavaScript
<body oncontextmenu="return false"></body>
2. Disable Right click from a particular element using jQuery
Bind contextmenu
event on an element from which you want to disable right-click.
Example –
Bind contextmenu
event on a <textarea id='address'>
.
$(document).ready(function(){ $("#address").bind('contextmenu', function (e) { $("#error").fadeIn("slow"); setTimeout(function(){ $("#error").fadeOut("slow"); },2000); return false; }); });
3. Disable cut, copy, and paste using jQuery
By blocking the mouse right-click, you’ve prevented users from copying your content that way. However, they can still copy it using keyboard shortcuts.
To prevent this, you should link the cut, copy, and paste events to the document or a specific element.
Example –
$('body').bind('cut copy paste', function (e) { $("#error").fadeIn("slow"); setTimeout(function(){ $("#error").fadeOut("slow"); },2000); return false; });
4. Conclusion
Using this you can stop the user from copying your content. However, it is not the best way to protect your content from copying because it is JavaScript-based code that the user can disable from its browser or copy content from the view source of the web page.
But it is somewhat better than allowing direct copying of content.
If you found this tutorial helpful then don't forget to share.