Files
30-seconds-of-code/snippets/copyToClipboard.md
Angelos Chalaris ea531aae03 Add copyToClipboard
2017-12-31 11:40:33 +02:00

621 B

copyToClipboard

Copy a string to the clipboard.

Create a new <textarea> element, fill it with the supplied data and add it to the HTML document. Use document.execCommand('copy') to copy to the clipboard. Finally, remove the <textarea> element from the HTML document.

const copyToClipboard = str => {
  const el = document.createElement('textarea');
  el.value = str;
  el.setAttribute('readonly', '');
  document.body.appendChild(el);
  el.select();
  document.execCommand('copy');
  document.body.removeChild(el);
}
copyToClipboard('Lorem ipsum'); // 'Lorem ipsum' copied to clipboard.