Copying strings to the clipboard using pure Javascript

This post is also available in: deDeutsch (German)

In order to copy a string to the system clipboard in the browser without using any dependency like clipboard.js, use this function:

function copyStringToClipboard (str) {
   // Create new element
   var el = document.createElement('textarea');
   // Set value (string to be copied)
   el.value = str;
   // Set non-editable to avoid focus and move outside of view
   el.setAttribute('readonly', '');
   el.style = {position: 'absolute', left: '-9999px'};
   document.body.appendChild(el);
   // Select text inside element
   el.select();
   // Copy text to clipboard
   document.execCommand('copy');
   // Remove temporary element
   document.body.removeChild(el);
}

Note: If the user selected anything when you ran the function, this selection will be cleared. If you need to preserve the selection, see this Hackernoon article for a more elaborate solution..

You can use it like this:

// Usage example:
copyStringToClipboard("abc123");

Browser compatibility

This solutions uses only basic Javascript (no ES6 features required), the DOM API which has existed for decades and document.exec('copy'); which is, according to the Mozilla Developer’s network, compatible with all major browsers, including Internet Explorer starting from IE9.

How it works

We create a new <textarea> element whose value we set to the string to copy (e.g. "abc123" in our usage example above).

In order to avoid confusing the user and, more importantly, screenreaders, we set it to readonly and shift it -9999px to the left, which is guaranteed to be outside the viewport for all practical purposes.

Only after shifting the element outside the viewport, we add it to the DOM so that it won’t be shown even for a fraction of a second.

Now we can select the text inside the element using el.select() and copy it to the clipboard using document.execCommand('copy');.

Finally, we remove the element from the DOM.

Credits to Angelos Charalis on Hackernoon for the original idea of moving the element outside the viewport.