0

I have a set p element which contains a link. I would like for the user to click a button, and it gets the value of the p element and copies it to the user's clipboard.

function copy() {
  document.getElementById("link").copy;
}
#link {
  color: blue;
}
<p id="link" onclick="copy()">https://www.spotify.com/us/</p>
hiphopfeels
  • 57
  • 1
  • 10
  • Does this answer your question? [How can I copy to clipboard in HTML5 without using flash?](https://stackoverflow.com/questions/26336138/how-can-i-copy-to-clipboard-in-html5-without-using-flash) – Theraot Apr 25 '20 at 17:38

4 Answers4

2

function copy() {
  var copyText = document.getElementById("link").innerText;
  var elem = document.createElement("textarea");
  document.body.appendChild(elem);
  elem.value = copyText;
  elem.select();
  document.execCommand("copy");
  document.body.removeChild(elem);
  alert("Copied the text");
}
#link {
  color: blue;
}
<p id="link" onclick="copy()">https://www.spotify.com/us/</p>

Your copy function can be as follows

function copy() {
  var copyText = document.getElementById("link").innerText;
  var elem = document.createElement("textarea");
  document.body.appendChild(elem);
  elem.value = copyText;
  elem.select();
  document.execCommand("copy");
  document.body.removeChild(elem);
  alert("Copied the text");
}
Sachin
  • 911
  • 8
  • 12
0

try this as the copy function

var text =  document.getElementById("link");
text.select();
document.execCommand("copy);
0

you can use input to copy text on clipboard

function copy() {
    /* Get the text field */
    var copyText = document.getElementById("link");

    /* Select the text field */
    copyText.select();
    copyText.setSelectionRange(0, 99999); /*For mobile devices*/

    /* Copy the text inside the text field */
    document.execCommand("copy");
    console.log("copied!");
}
<input id="link" onclick="copy()" value="https://www.spotify.com/us/">

Or if you want to use p then yuo can use this trick

function copy() {
    /* Get the text field */
    var copyText = document.getElementById("link");
    var copyP = document.getElementById("link_p");
    copyText.value=copyP.innerHTML;

    /* Select the text field */
    copyText.select();
    copyText.setSelectionRange(0, 99999); /*For mobile devices*/

    /* Copy the text inside the text field */
    document.execCommand("copy");
    console.log("copied!");
}
<input type="text" id="link" value="" style="display:none">
<p id="link_p" onclick="copy()">text</p>
giovybus
  • 349
  • 1
  • 3
  • 10
0

function copy() {
  document.getElementById("link").copy;
}
#link {
  color: blue;
}
<p id="link" onclick="copy()">https://www.spotify.com/us/</p>
Mukoro Godwin
  • 120
  • 1
  • 9