Copy text to clipboard using [Vanilla] JavaScript

17 October 2017 — Written by Bharat
#javascript#frontend

In the browser context, the document node has execCommand method, which has the following syntax:

document.execCommand(aCommandName, aShowDefaultUI, aValueArgument)

This method can do many magical things, one of which is copying text to the clipboard.

For this, simply use "Copy" in place of aCommandName in the syntax mentioned above, like this:

// myInputElement is some <input type="text"> element
// Select the value/contents of the element
myInputElement.select();
// Copy it to clipboard
document.execCommand("Copy");

But wait, there’s a little thing to know here.

For copying the text, you need to select it. But select doesn’t works for every HTML element. I specifically used the input element here because it is one of the elements which supports select() (since it becomes an editable region easily and the execCommand() affects the editable region only and blah blah boring stuff).

Long story short, for the easiest use-case, you need an <input type="text"> element, and you can then select it and execute the copy command on it.

But what if you wanted to select and copy text from some other element, say some <h1> tag? Easy:

  1. Get the text that you want to copy in a variable, using innerText() on the element
  2. Create a temporary <input type="text"> element
  3. Set the value of this temporary input element to whatever text you want to copy
  4. Append the temporary input element to document.body using appendChild()
  5. Use select() method to select the (text of) the appended input element
  6. Use document.execCommand("Copy"); [Notice the capital C in Copy]
  7. Now our work is done, but make sure to not leave that temporary element in the document, remove it using removeChild()
  8. Congrats, the text has been copied to clipboard now, paste it wherever you want to see if it worked for you

Here is the easy code for the above, wrapped in a function for you:

// @param element: the reference to the target HTML element
// (whose text you want to copy), which you may get by using
// document.querySelector() or document.getElementById() and so on..]

function copyText(element) {
 
 var textToCopy = element.innerText;
 
 var myTemporaryInputElement = document.createElement("input");
 myTemporaryInputElement.type = "text";
 myTemporaryInputElement.value = textToCopy;
 
 document.body.appendChild(myTemporaryInputElement);
 
 myTemporaryInputElement.select();
 document.execCommand("Copy");
 
 document.body.removeChild(myTemporaryInputElement);
}

And finally a working pen showing the same:

https://codepen.io/bharatramnani94/pen/bYqbZm

Related links:

A lot more is possible with document.execCommand, including some very cool things, but we'll leave those for another day. Feel free to email me at bharatramnani94@gmail.com if you want to learn more about topics related to this, or any other topic for that matter.