Search code examples
javascriptnode.jsexpress-handlebars

Copy to Clipboard in NodeJs with Express Handlebars template engine


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


Solution

  • 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/