Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 418
Ivan Avatar asked Mar 01 '18 15:03

Ivan


People also ask

How to copy text from input tag to clipboard using JavaScript?

You can simply use opacity:0.00000000000001 to hide the input tag, then use javascript to copy the hidden text to clipboard function myFunction () { var copyText = document.getElementById ("myInput"); copyText.select (); copyText.setSelectionRange (0, 99999) document.execCommand ("copy"); alert ("Text copied successfully"); }

Why does the Office Clipboard not copy images?

The clipboard would copy 'text only' and no images, but now works perfectly. The issue was the installation of a new firewall. The solution was to set firewall permissions for Office 365 and the Office clipboard began working fine. Was this reply helpful?

Why can’t I See my clipboard history?

If the Clipboard history button is disabled, toggle it on. Do note that when this option is disabled, your system will be able to paste only the most recent item on your clipboard, and you won’t be able to access your clipboard history.

Why is my clipboard not working on Windows 10?

The first step in resolving this issue for me was to disable all firewalls to then test the clipboard functions. If this step works, then open your firewall manager and add Office to the permissions list and save the setting. Was this reply helpful?


2 Answers

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">
like image 166
isherwood Avatar answered Oct 07 '22 11:10

isherwood


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">
like image 35
Patrick Roberts Avatar answered Oct 07 '22 11:10

Patrick Roberts