简体   繁体   中英

Copy Text to Clipboard when Text is clicked

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?

 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);
};

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM