Add copyToClipboard

This commit is contained in:
Angelos Chalaris
2017-12-31 11:40:33 +02:00
parent ff7a348da6
commit a5cc5ac6c7
2 changed files with 24 additions and 0 deletions

View File

@ -0,0 +1,23 @@
### 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.
```