Search code examples
javascriptwordpressfunctioncopygetselection

Place small "Copied" confirmation in the div that is copied by click


I have a wordpress site with a DIV that I copy its content via a link using a simple javascript code. I need a message to replace the copied content saying "Copied" in the div AFTER its copied.

Very challenging. Need help to do this.

<div class="btcTXT" id="btc">bc1q978cape6n3sez2ahp59s7jr59j70nqq2x3tt8c</div>
<div onclick="CopyToClipboard('btc');return false;"  class="cpy"><i class="far fa-copy"></i> </div>



<script>
function CopyToClipboard(id)
{
var r = document.createRange();
r.selectNode(document.getElementById(id));
window.getSelection().removeAllRanges();
window.getSelection().addRange(r);
document.execCommand('copy');
window.getSelection().removeAllRanges();
}
</script>

enter image description here


Solution

  • You're almost there...

    function CopyToClipboard(id) {
      let item = document.getElementById(id);
      var r = document.createRange();
      r.selectNode(item);
      window.getSelection().removeAllRanges();
      window.getSelection().addRange(r);
      document.execCommand('copy');
      window.getSelection().removeAllRanges();
      item.innerText = 'Copied';
    }