This tutorial demonstrates how to copy text on clicking HTML element using jQuery.
Here I have HTML elements that I will transform these clickable.
<p>List of codes you can use <b>(Click element to copy to clipboard)</b>
<ul>
<li class="clickToCopy">[FIRSTNAME]</li>
<li class="clickToCopy">[LASTNAME]</li>
<li class="clickToCopy">[EXPIRYDATE]</li>
</ul>
<div id="copiedToClipBoard" class="text-success"></div>
</p>
This is the background prcoess
- Create a temporarily hidden text field (<input>).
- Copy the content of the element to the created text field.
- Select the content of the text field.
- Execute the command copy using document.exeCommand(‘copy”).
- Remove the temporary text field.
$(".clickToCopy").click(function (e) {
e.preventDefault();
var $temp = $("<input>");
$("body").append($temp);
$temp.val($(this).text()).select();
document.execCommand("copy");
$temp.remove();
$("#copiedToClipBoard").html("Copied to clipboard");
});
Done! Now you can click the list to copy into your clipboard.
Don’t forget to change CSS to make the elements clickable type.
.clickToCopy{
cursor:pointer;
}