Reputation: 1
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?
Upvotes: 0
Views: 485
Reputation: 1643
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);
};
Upvotes: 1
Reputation: 2319
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);
Upvotes: 0