You can't copy content from an element that is not being displayed. However, pulling the holder out of the document flow (so it doesn't alter the layout of the rest of the elements on the page) and then changing its opacity
to become transparent will work because, even when opacity
is 0
, the element is still considered to be visible (go figure!).
You also, need to be careful because not all browsers support .execCommand()
and if they don't, they will throw an error, so a try/catch
is warranted.
var input = document.getElementById("data");
var temp = document.getElementById("temp");
// Add copy click event handler to the body so that anytime a copy operation occurs
// our event handler will fire
document.body.addEventListener('click', copy);
// event handler will recieve argument referencing the event itself
function copy(e) {
// copy data to placeholder - Don't use .innerText, use .textContent
temp.value = data.textContent;
// is element selectable?
if (temp.select) {
// select text
temp.select();
// Not all browsers implement execCommand and, if they don't,
// an error will be thrown.
try {
// copy text
document.execCommand('copy');
} catch (err) {
alert('please press Ctrl/Cmd+C to copy manually');
}
}
}
#temp {
position:absolute;
opacity:0;
}
#copytext {
height:150;width:162;background-color:pink
}
<input type="text" id="temp">
<p id="data">data to copy<p>
<button>Copy</button>
*This solution was adapted from here.