JavaScript copy to clipboard not working
A more recent solution (year 2020) uses the new Clipboard API writeText method which is supported by most modern browsers (see Can I use for more details).
//If you want to copyText from Element
function copyTextFromElement(elementID) {
let element = document.getElementById(elementID); //select the element
let elementText = element.textContent; //get the text content from the element
copyText(elementText); //use the copyText function below
}
//If you only want to put some Text in the Clipboard just use this function
// and pass the string to copied as the argument.
function copyText(text) {
navigator.clipboard.writeText(text);
}
<div id="mytext">This is some text that needs to be copied</div>
<button onclick="copyTextFromElement('mytext')">Copy</button>
This will allow you to copy the text of an element. Though I have not tested it with complicated layout.
If you want to use this then remove the alerts and provide a better way to let the user know the content was copied.
SAFARI: This does not work on Safari before version 10.0. But as of Safari 10.0 this now works.
function copyText(element) {
var range, selection, worked;
if (document.body.createTextRange) {
range = document.body.createTextRange();
range.moveToElementText(element);
range.select();
} else if (window.getSelection) {
selection = window.getSelection();
range = document.createRange();
range.selectNodeContents(element);
selection.removeAllRanges();
selection.addRange(range);
}
try {
document.execCommand('copy');
alert('text copied');
}
catch (err) {
alert('unable to copy text');
}
}
<h1 id='display' onClick='copyText(this)'>Text Sample</h1>
If you want to use this on an <input>
or <textarea>
element then let me know the code is different.
The try/catch is for older versions of Safari that would throw an exception. So if you don't plan to support Safari before version 10.0 then you can remove it.
select()
method is used to select the contents of text fields. it won't work on h1
element.
Great answer by Intervalia.
Small improvement to it, sometimes the clicked element is not the one you want to copy.
So I suggest you pass the id of the element you want to copy.
<button onClick='copyText("display")'> Copy </button>
<h1 id='display'> Text Sample </h1>
And then, in the first line of your function do
element = document.getElementById(element);
Not much of a difference but I think it's more useful this way.