jQuery – How to copy text on clicking an element

January 22, 2022

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

  1. Create a temporarily hidden text field (<input>).
  2. Copy the content of the element to the created text field.
  3. Select the content of the text field.
  4. Execute the command copy using document.exeCommand(‘copy”).
    1. 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;
}