Yesterday we saw how we can use the new and improved Clipboard API to copy text to our clipboard. But if we want to have some more support we need to use the old version which is
<input type="text" id="copy" value="VcaXAXfUxXcHywAhiWXraPPNjY9hgV" />
The HTML is basically the same as for the Clipboard API, only now we can only use
Then for the
// Only fire if the target has id copy
if (!event.target.matches('#copy')) return;
document.getElementById('copy-status').innerText = 'Copied to clipboard';
document.getElementById('copy-status').innerText = 'Click to copy';
First, we add an
eventListener on the click event. This one fires on ALL click events, but inside we tell it to return if the id of the target is not
This is called
event delegation, more about that in another day's article
Then we programmatically select all the text in our
input field. Next, we run the magic command:
document.execCommand("copy"); this will copy the text into your clipboard.
Then we do some fancy magic by updating the text under it, to notify the user it has been copied. And set a timeout of 1200ms to revert is back to its old value. (This last part is optional of-course)
Feel free to play around with this Codepen.
Browser support permalink
This function is quite widely supported, more than the succesor Clipboard API.