Vanilla JavaScript Copy Text to Clipboard with document.execCommand


How to copy to Clipboard using Vanilla JavaScript document.execCommand

8 Apr, 2020 · 2 min read

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:

  function (event) {
    // Only fire if the target has id copy
    if (!'#copy')) return;;

    document.getElementById('copy-status').innerText = 'Copied to clipboard';
    setTimeout(function () {
      document.getElementById('copy-status').innerText = 'Click to copy';
    }, 1200);

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.

Document execCommand browser support

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

Spread the knowledge with fellow developers on Twitter
Tweet this tip
Powered by Webmentions - Learn more

Read next 📖

Removing all vowels with JavaScript

3 Dec, 2022 · 2 min read

Removing all vowels with JavaScript

10 games to learn JavaScript

2 Dec, 2022 · 3 min read

10 games to learn JavaScript

Join 2099 devs and subscribe to my newsletter