I am trying to add button to copy simple text string but without success.
You can't .select()
a hidden element that has visibility: hidden;
or display: none;
but you can do something like this:
function kopiraj() {
var copyText = document.getElementById("toCopy");
copyText.select();
document.execCommand("Copy");
}
[aria-hidden="true"] {
opacity: 0;
position: absolute;
z-index: -9999;
pointer-events: none;
}
<button type="button" onclick="kopiraj()">Copy</button>
<input type="text" id="toCopy" value="123456789" aria-hidden="true">
Instead of the hidden
attribute, use an offscreen class and the aria-hidden
attribute (the latter for accessibility):
.offscreen {
position: absolute;
left: -999em;
}
<input ... class="offscreen" aria-hidden="true">
You cannot select a hidden element.
Best way is to copy the value in the element to another visible element.
As you can see, I created a textarea
with an absolute position and set the top and left to -9999px. So now, you can copy the value in the hidden element
to the textarea
and then cope the value in the textarea
to the clipboard
function kopiraj() {
var copyFrom = document.getElementById("toCopy"); //Value to copy
var copyTo = document.getElementById("valueToCopy"); //Visible element to copy the value to
copyTo.value = copyFrom.value; //Fill the visible element with the value to copy
copyTo.select(); //Select the value
document.execCommand("Copy"); //Copy
copyTo.value = ""; //Empty the visible element after copy
}
.valueToCopy{
position: absolute;
top: -9999px;
left: -9999px;
opacity: 0;
}
<textarea class="valueToCopy" id="valueToCopy"></textarea>
<button type="button" onclick="kopiraj()">Copy</button>
<input type="hidden" id="toCopy" value="123456789">
I've successfully used this JavaScript code which doesn't require any new HTML elements:
var text = ...;
var listener = function(ev) {
ev.clipboardData.setData("text/plain", text);
ev.preventDefault();
};
document.addEventListener("copy", listener);
document.execCommand("copy");
document.removeEventListener("copy", listener);