Ivan
Ivan

Reputation: 191

Hidden element won't copy to clipboard

I am trying to add button to copy simple text string but without success.

function kopiraj() {
  var copyText = document.getElementById("toCopy");
  copyText.select();
  document.execCommand("Copy");
  document.getElementById("telefon").innerHTML = 'Copied';
}
<button type="button" onclick="kopiraj()">Copy</button>
<input type="hidden" id="toCopy" value="123456789">
<p id="telefon"></p>

It does not put anything in Clipboard.

I do not need input field. I can add text in JS itself.

Upvotes: 9

Views: 8330

Answers (4)

Barzee
Barzee

Reputation: 905

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

Upvotes: 0

Mario Rawady
Mario Rawady

Reputation: 871

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">

Upvotes: 0

Patrick Roberts
Patrick Roberts

Reputation: 51886

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">

Upvotes: 8

isherwood
isherwood

Reputation: 61083

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">

Upvotes: 27

Related Questions