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

24 lines
621 B
Markdown

### 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.
```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.
```