Files
30-seconds-of-code/snippets/copyToClipboard.md
2017-12-31 11:55:58 +02:00

24 lines
699 B
Markdown

### copyToClipboard
Copy a string to the clipboard. Only works as a result of user action (i.e. inside a `click` event listener).
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.
```js
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);
}
```
```js
copyToClipboard('Lorem ipsum'); // 'Lorem ipsum' copied to clipboard.
```