0

I'm trying to send a text using js function and copy it to clipboard, but somehow can't find a practical solution online. All I found are about copying from an element.

Is it possible to do it? I'll be really thankful if you help.

<a onClick="CopyToClipboard('{{ product.link }}')"><i class="fa fa-copy">Copy</i></a>

function CopyToClipboard(link) {
  link.select();
  document.execCommand("Copy");
  alert("Copied the text: " + link);
}

I also tried this:

function CopyToClipboard(link) {
if (document.selection) { 
        var range = document.body.createTextRange();
        range.moveToElementText(link);
        range.select().createTextRange();
        document.execCommand("copy"); 

} else if (window.getSelection) {
        var range = document.createRange();
         range.selectNode(link);
         window.getSelection().addRange(range);
         document.execCommand("copy");
         alert("text copied") 
}}

https://jsfiddle.net/hLw98t1c/7/

Kardo
  • 1,658
  • 4
  • 32
  • 52
  • Possible duplicate of [How do I copy to the clipboard in JavaScript?](https://stackoverflow.com/questions/400212/how-do-i-copy-to-the-clipboard-in-javascript) – Rory O'Kane Feb 16 '18 at 21:24

1 Answers1

0

Found it: https://codepen.io/shaikmaqsood/pen/XmydxJ/

function copyToClipboard(element) {
    var $temp = $("<input>");
    $("body").append($temp);
    $temp.val(element).select();
    document.execCommand("copy");
    $temp.remove();
}
Kardo
  • 1,658
  • 4
  • 32
  • 52