Disable Right click and cut copy paste with jQuery

In this quick tutorial, I show How you can disable Right-click and keyboard shortcut of cut,copy, and paste from the whole document or in a particular element using jQuery.

You can find this type of functionality mainly in Test based web application where student not allowed to copy and paste content on the page.

When it’s required?

There are many cases where you can use it.

For example – You want to change the behavior of Right click and show your own context menu or For stopping the user to copy your page contents.

Disable Right click and cut copy paste with jquery

For downloading, all examples codes of this tutorial click Download button.


Contents

  1. Disable in whole document
  2. From a particular element
  3. Disable cut,copy, and paste
  4. Conclusion

1. Disable Right click from the whole document

By this way, you can disable Right-click from the whole document/web page.

Example –

Within example, I only use setTimeout() function to show the message on the screen for given time.

You can either use return false or e.preventDefault() to disable the Right click. I used return false in the example.

$(document).bind('contextmenu', function (e) {
 
  $("#error").fadeIn("slow");
  setTimeout(function(){
   $("#error").fadeOut("slow");
  },2000);
  return false;
 
});

Using JavaScript

<body oncontextmenu="return false"></body>

Output –

Right, click to see the changes.


2. From a particular element

Bind contextmenu event on an element from which you want to disable right-click.

Example –

Binding 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;
 
  });
 
});

Output –

Right, click on Address textarea.


3. Disable cut,copy, and paste

You have stop user from copying your content by disabling mouse right-click. But the user can also able to copy your content simply using keyboard shortcut keys.

For disabling this you need to bind cut copy paste event to the document or an element.

Example –

$('body').bind('cut copy paste', function (e) {
 $("#error").fadeIn("slow");
 setTimeout(function(){
  $("#error").fadeOut("slow");
 },2000);
 
 return false;
});

Output-

Try to copy text and paste text in textarea.


4. Conclusion

Using this you can stop the user from copying your content. But it is not the best way to protect your content from copying because it is JavaScript-based code which the user can disable from its browser or he/she can either copy content from view-source of the web page.

But it is somewhat better than allowing directly copying content.

Related Post

Spread the love

One Comment

  1. Nikhil Kamble said:

    Thanks…..

    May 18, 2017
    Reply

Leave a Reply

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