Add copyToClipboard
This commit is contained in:
23
snippets/copyToClipboard.md
Normal file
23
snippets/copyToClipboard.md
Normal 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.
|
||||
```
|
||||
Reference in New Issue
Block a user