2

How we can implement copy to clipboard feature on button click in NodeJs using express handlebar template.

I have tried using Javascript but it's not working.

Below is the code which I have tried:

myFile.handlebars :

<input type="button" id="linkBtn" class="btn btn-primary" onclick="copyLink()" data-toggle="tooltip" title="Copy to Clipboard" value="copy link" readonly />

<script>
  function copyLink() {
    let copyText = document.getElementById("linkBtn");
    /* Select the text field */
    copyText.select();
    /* Copy the text inside the text field */
    document.execCommand("copy");

    /* Alert the copied text */
    //alert("Copied the text: " + copyText.value);
  }
</script>

Copy to the clipboard using JS

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Zarna Borda
  • 695
  • 1
  • 6
  • 22

1 Answers1

2

You trying to copy text from the button. you can select button text. add content which you want to select in any other tag

here is a solution:

<input type="button"  class="btn btn-primary" onclick="copyLink()" data-toggle="tooltip" title="Copy to Clipboard" value="copy link" readonly />

<span id="copyText">Copy this Text</span>

<script>
  function copyLink() {
    let copyText = document.getElementById("copyText") 

    var selection = window.getSelection();

    var range = document.createRange();

    range.selectNodeContents(copyText);

    selection.removeAllRanges();

    selection.addRange(range);

    document.execCommand('copy');
  }
</script>

here is a working demo: https://jsfiddle.net/5mryvpc6/

Shashin Bhayani
  • 1,551
  • 3
  • 16
  • 37