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 document.execCommand()
.
How to copy text with Vanilla JavaScript document.execCommand()
<input type="text" id="copy" value="VcaXAXfUxXcHywAhiWXraPPNjY9hgV" />
The HTML is basically the same as for the Clipboard API, only now we can only use input
or textareas
.
Then for the JavaScript
part, we can do the following:
document.addEventListener(
'click',
function (event) {
// Only fire if the target has id copy
if (!event.target.matches('#copy')) return;
event.target.select();
document.execCommand('copy');
document.getElementById('copy-status').innerText = 'Copied to clipboard';
setTimeout(function () {
document.getElementById('copy-status').innerText = 'Click to copy';
}, 1200);
},
false
);
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 copy
.
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.
See the Pen Vanilla JavaScript Copy Text to Clipboard with Document.execCommand by Chris Bongers (@rebelchris) on CodePen.
Browser support
This function is quite widely supported, more than the succesor Clipboard API.
Thank you for reading, and let’s connect!
Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter