Copy Data to Clipboard Using jQuery
In this post, find jQuery solution to allow users to copy data to clipboard. 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.
Here is the jQuery solution to copy data to clipboard using jQuery:
[javascript]
$(function() {
$('.allowCopy').click(function() {
$(this).focus();
$(this).select();
document.execCommand('copy');
});
});
[/javascript]
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.execCommand('copy'); command which will copy the data. Below is HTML code:
[html]
<input readonly type="text" value="Click Me To Copy" class="allowCopy noselect">
[/html]
Here is the jQuery code to disable right click on your website:
[javascript]
$(function(){
$(document).on("contextmenu",function(e){
e.preventDefault();
});
});
[/javascript]
You can use following CSS class to disable text selection on your website:
[css]
.noselect {
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
[/css]