The below code snippet allows users to select and copy data to the clipboard in a single click using JQuery.

In the web world, it's all about great user experience. Many times we need to use the data to copy paste from one place to another. If you are providing the CDN or any other data on your web pages, it will be great to use this functionality as it allows users to select and copy the target data in a single click event.

Let's see how do we do it.

The JQuery goes like this -

$(function() {
$('.copy-to-clipboard input').click(function() {
$(this).focus();
$(this).select();
document.execCommand('copy');
$(".copied").text("Copied to clipboard").show().fadeOut(1200);
});
});

In above script, first, we trigger the click event on the targeted data element and run the select() function. Then simply we run document.execCommand() function which copies the data.

The very last line of script simply alert the event action and put the message 'Copied to clipboard' in the first line of the HTML code below.

HTML -

<div class='copied'></div>

<div class="copy-to-clipboard">
<input readonly type="text" value="Click Me To Copy">
</div>

 A little bit CSS for beautification -

.copy-to-clipboard input {
border: none;
background: transparent;
}

.copied {
position: absolute;
background: #1266ae;
color: #fff;
font-weight: bold;
z-index: 99;
width: 100%;
top: 0;
text-align: center;
padding: 15px;
display: none;
font-size: 18px;
}

That is all. See the demo below with the same code snippet-