0

I got a Website where a Invite-Link is displayed within <h2> tags

I simply want to copy the text to clipboard when the text itself is clicked.

my code looks like this:

<script>
  function CopyInviteLink() {
    var copyText = document.getElementById("invite-link");
    copyText.select();
    copyText.setSelectionRange(0, 99999)
    document.execCommand("copy");
  }

function setInviteLink(roomID) {
  const inviteLink = window.location.href + "/join.html?room=" + roomID;
  document.getElementById("invite-link").innerText = inviteLink;
}
</script>
<h2 id="invite-link" onclick="myFunction()"></h2><br>

I tried this method: https://www.w3schools.com/howto/howto_js_copy_clipboard.asp

which uses the following method: (document.execCommand("copy"))
but this does seem to only work with <input type="text">, but I would like to only have a clean text, not the "text input" style

could someone help me or link a solution?

T-Coro
  • 1
  • 1
  • Does this answer your question? [How to copy String into Clipboard using a onClick Eventlistener](https://stackoverflow.com/questions/53043803/how-to-copy-string-into-clipboard-using-a-onclick-eventlistener) – Zohir Salak Apr 14 '20 at 13:23

2 Answers2

1

const copyToClipboard = str => {
  const el = document.createElement('textarea');
  el.value = document.getElementById("invite-link").innerHTML;
  el.setAttribute('readonly', '');
  el.style.position = 'absolute';
  el.style.left = '-9999px';
  document.body.appendChild(el);
  el.select();
  document.execCommand('copy');
  alert("Copied the text: " + el.value);
  document.body.removeChild(el);
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h2 id="invite-link" onclick="copyToClipboard()">heading</h2><br>

Try this:

const copyToClipboard = str => {
  const el = document.createElement('textarea');
  el.value = str;
  el.setAttribute('readonly', '');
  el.style.position = 'absolute';
  el.style.left = '-9999px';
  document.body.appendChild(el);
  el.select();
  document.execCommand('copy');
  document.body.removeChild(el);
};
Ramlal S
  • 1,131
  • 1
  • 11
  • 25
0

This will work for you

here textToCopy is the value of input

 var input = document.createElement("textarea");
     document.body.appendChild(input);
     input.value = document.getElementById("invite-link").value;
     input.select();
     document.execCommand("copy");
     document.body.removeChild(input);
Narendra Chouhan
  • 2,140
  • 1
  • 9
  • 17