How to copy text to clipboard using JavaScript?

Posted Jun 27, 20202 min read

When building a website, a very common requirement is the ability to copy text to the clipboard by clicking a button. Javascript can easily do this in five short steps:no need for the user to select it or type the appropriate key combination on the keyboard.

  1. Create an element of <textarea> to be attached to the document. Set its value to the string we want to copy to the clipboard.
  2. <textarea> appends this element to the current HTML document.
  3. Use HTMLInputElement.select() to select the content<textarea> element.
  4. Use Document.execCommand('copy') to copy <textarea> to the clipboard.
  5. <textarea> deletes elements from the document.

The simplest version of this method is as follows:

const copyToClipboard = str => {
  const el = document.createElement('textarea');
  el.value = str;
  document.body.appendChild(el);
  el.select();
  document.execCommand('copy');
  document.body.removeChild(el);
};

Please keep in mind that this method will not be used everywhere, but only because of the way the user operates(for example, inside the click event listener), because this way Document.execCommand() works .

Hide additional elements

Although the above method can be used, there may be some problems, such as flickering when adding and deleting, and <textarea> is more obvious when considering accessibility. The main improvement of this method comes from adding some CSS to make the element invisible and restrict user editing:

const copyToClipboard = str => {
  const el = document.createElement('textarea');
  el.value = str;
  el.setAttribute('readonly','');
  el.style.position ='absolute';
  el.style.left ='-9999px';
  document.body.appendChild(el);
  el.select();
  document.execCommand('copy');
  document.body.removeChild(el);
};

Save and restore original document selection

The final consideration before concluding is to respect the user s previous interaction with the website, for example, some content has been selected. Fortunately, we can now use some modern Javascript methods and properties, such as DocumentOrShadowRoot.getSelection(), Selection.rangeCount and Selection.getRangeAt(), Selection.removeAllRanges() and Selection. addRange() Save and restore original document selection.


THE END

Thanks for reading