Vanilla JavaScript Copy Text to Clipboard with Clipboard API

— 4 minute read

permalink

You have probably seen these API keys you just have to click it and it will be under your copy.

These are pretty easy to make see how!

How to copy text with Vanilla JavaScript Clipboard API permalink

<input type="text" id="copy" value="VcaXAXfUxXcHywAhiWXraPPNjY9hgV" />

All we really need is a input or textarea or plain element we can copy from.

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;

if (!navigator.clipboard) {
// Clipboard API not available
return;
}
var text = event.target.value;
try {
navigator.clipboard.writeText(text);
document.getElementById('copy-status').innerText = 'Copied to clipboard';
setTimeout(function() {
document.getElementById('copy-status').innerText = 'Click to copy';
}, 1200);
} catch (err) {
console.error('Failed to copy!', err);
}
},
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 check if we have access to navigator.clipboard this is due to the Clipboard API. It's a relatively new option and a successor of the document.execCommand() function.

If we do have access the get the specific text, in this case, we use event.target.value since we are copying from an input field.

We then wrap the actual function inside a try...catch in case this might still fail.

We call the function: navigator.clipboard.writeText(text); which will actually add the text variable to our 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 Clipboard API by Chris Bongers (@rebelchris) on CodePen.

Browser support permalink

Unfortionally this super awesome function does not have the best browser support, but it's worth using. Tomorrow we will work on the old method of copying to Clipboard.

Clipboard writeText browser support

Thank you for reading, and let's connect! permalink

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter