I\'ve been trying to copy the innerContent
of a to my clipboard without success:
You could do this: create a temporary text area and append it to the page, then add the content of the span
element to the text area, copy the value from the text area and remove the text area.
Because of some security restrictions you can only execute the Copy
command if the user interacted with the page, so you have to add a button and copy the text after the user clicks on the button.
document.getElementById("cp_btn").addEventListener("click", copy_password);
function copy_password() {
var copyText = document.getElementById("pwd_spn");
var textArea = document.createElement("textarea");
textArea.value = copyText.textContent;
document.body.appendChild(textArea);
textArea.select();
document.execCommand("Copy");
textArea.remove();
}
<span id="pwd_spn" class="password-span">Test</span>
<button id="cp_btn">Copy</button>
See https://stackoverflow.com/a/48020189/2240670 there is a snippet of code for that gives you an example for a div, that also applies to a span, I did not copy it here to avoid duplication.
Basically, when you are copying to clipboard you need to create a selection of text, <textarea>
and <input>
elements make this easy because they have a select()
method, but if you are trying to copy contents from any other type of element like a <div>
or <span>
, you'll need to:
Range
object(some browsers do not provide a constructor, or a decent way to do this). Calling document.getSelection().getRangeAt(0)
, I found works on most browsers except edge(ie11 works though).Selection
.document.execCommand("copy")
to copy the selected text.I also recommend checking the API of Selection
and Range
, that will give you a better grasp of this.
simple method
1)create a input
2)give style z-index -1 and it will be hide
var code = $("#copy-to-clipboard-input");
var btnCopy = $("#btn-copy");
btnCopy.on("click", function () {
code.select();
document.execCommand("copy");
});
<input type="input" style="width:10px; position:absolute; z-index: -100 !important;" value="hello" id="copy-to-clipboard-input">
<button class="btn btn-success" id="btn-copy">Copy</button>