A very common need when building websites is the ability to copy text to clipboard with a single button click. Javascript can easily do this in five short steps:
<textarea>
element to be appended to the
document. Set its value to the string that we want to copy to the
clipboard.
<textarea>
element to the current HTML
document.
HTMLInputElement.select()
to select the contents of the
<textarea>
element.
Document.execCommand('copy')
to copy the contents of
the <textarea>
to the clipboard.
<textarea>
element from the document.
The simplest version of this method looks something like this:
const copyToClipboard = str => {
const el = document.createElement('textarea');
.value = str;
eldocument.body.appendChild(el);
.select();
eldocument.execCommand('copy');
document.body.removeChild(el);
; }
Bear in mind that this method will not work everywhere, but only as a
result of a user action (e.g. inside a click
event listener),
due to the way Document.execCommand()
works.
The above method, while functional, might have some issues such as
flashing when appending and removing the <textarea>
, a
problem that is even more apparent when considering accessibility. A major
improvement to this method comes from adding some CSS to make the element
invisible and restrict editing by users:
const copyToClipboard = str => {
const el = document.createElement('textarea');
.value = str;
el.setAttribute('readonly', '');
el.style.position = 'absolute';
el.style.left = '-9999px';
eldocument.body.appendChild(el);
.select();
eldocument.execCommand('copy');
document.body.removeChild(el);
; }
The final consideration before wrapping this up is respecting the user’s
previous interaction with the website, like having already selected some
content. Luckily, we can now use some modern Javascript methods and
properties like DocumentOrShadowRoot.getSelection()
,
Selection.rangeCount
, Selection.getRangeAt()
,
Selection.removeAllRanges()
and
Selection.addRange()
to save and restore the original
document selection. You can find the final code with these improvements
implemented in the
copyToClipboard snippet.