Copy Data to Clipboard Using jQuery


Copy Data to Clipboard Using jQuery

In this post you find jQuery solution to allow users to copy data to clipboard using jQuery. This solution is quite handy when right click is disabled for your website and also text selection is also disabled. When text selection is disabled along with right click, it’s difficult for users to select the text and then copy it. I hope you can find it useful.

Here is the jQuery solution:

1
2
3
4
5
6
7
$(function() {
   $('.allowCopy').click(function() {
     $(this).focus();
     $(this).select();
     document.execCommand('copy');
   });
});

The above jQuery code will allow click events for all HTML controls with a CSS class “allowCopy” and then select the text and execute document.exec Command(‘copy’); command which will copy the data. Below is HTML code:

1
<input readonly type="text" value="Click Me To Copy" class="allowCopy noselect">

Here is the jQuery code to disable right click on your website:

1
2
3
4
5
$(function(){
   $(document).on("contextmenu",function(e){
      e.preventDefault();
   });
});

You can use following CSS class to disable text selection on your website:

1
2
3
4
5
6
7
8
.noselect {
  -webkit-touch-callout: none;
  -webkit-user-select: none;   
  -khtml-user-select: none;    
  -moz-user-select: none;      
  -ms-user-select: none;      
  user-select: none;
}

Features:

  1. Create a <textarea> element to be appended to the document. Set its value to the string that we want to copy to the clipboard.
  2. Append said <textarea> element to the current HTML document.
  3. Use HTMLInputElement.select() to select the contents of the <textarea> element.
  4. Use Document.execCommand('copy') to copy the contents of the <textarea> to the clipboard.
  5. Remove the <textarea> element from the document.

 

Leave a Reply

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