Search code examples
jqueryselectclipboardcopy-pasteexeccommand

Jquery select() and copy text to clipboard is not working


I am trying to copy text from table rows to my clipboard, however, it does not work. I have logged the text from the row in the console when it selected and it shows, however select() and document.execCommand('copy') is not working with this.

This is the table

    <table class="table table-two">
        <div class="copied-toast"></div>
     <tr>
       <td>Login</td>
       <td class="copy-me">2090862973</td>
      <td>
         <div class="text-copy"><img src="../images/icons/fi_copy.svg" /> copy</div>
      </td>
      <td></td>
    </tr>
    <tr>
      <td>Password</td>
      <td class="copy-me">XNFRNFN</td>
      <td>
       <div class="text-copy"><img src="../images/icons/fi_copy.svg" /> copy</div>
     </td>
     <td><img src="../images/icons/key.svg" /> Change</td>
    </tr>
 </table>

This is the jquery

<script>
    $(function () {
        $(".copied-toast").hide();
        $(".text-copy").click(function () {
            $(this).closest("tr").find(".copy-me").select();
            document.execCommand('copy');
            $(".copied-toast").text("Copied!").show().fadeOut(1200);
        });
    });
</script>

Solution

  • I've found that document.execCommand() is now obselete so I used the Clipboard API

    $(function () {
        $(".copied-toast").hide();
        $(".text-copy").click(function () {
            var copiedtext = $(this).closest("tr").find(".copy-me").text();
            if (navigator.clipboard) {
                navigator.clipboard.writeText(copiedtext)
                    .then(() => {
                        $(".copied-toast").text("Copied!").show().fadeOut(1200);
                    })
                    .catch((error) => {
                        $(".copied-toast").text("Not copied!").show().fadeOut(1200);
                    });
            } else {
                $(".copied-toast").text("Not copied!").show().fadeOut(1200);
            }
    
        });
    });