Update copyToClipboard.md
This commit is contained in:
@ -3,8 +3,10 @@
|
|||||||
Copy a string to the clipboard. Only works as a result of user action (i.e. inside a `click` event listener).
|
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.
|
Create a new `<textarea>` element, fill it with the supplied data and add it to the HTML document.
|
||||||
|
Use `Selection.getRangeAt()`to store the selected range (if any).
|
||||||
Use `document.execCommand('copy')` to copy to the clipboard.
|
Use `document.execCommand('copy')` to copy to the clipboard.
|
||||||
Finally, remove the `<textarea>` element from the HTML document.
|
Remove the `<textarea>` element from the HTML document.
|
||||||
|
Finally, use `Selection().addRange()` to recover the original selected range (if any).
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const copyToClipboard = str => {
|
const copyToClipboard = str => {
|
||||||
@ -14,9 +16,14 @@ const copyToClipboard = str => {
|
|||||||
el.style.position = 'absolute';
|
el.style.position = 'absolute';
|
||||||
el.style.left = '-9999px';
|
el.style.left = '-9999px';
|
||||||
document.body.appendChild(el);
|
document.body.appendChild(el);
|
||||||
|
const selected = document.getSelection().rangeCount > 0 ? document.getSelection().getRangeAt(0) : false;
|
||||||
el.select();
|
el.select();
|
||||||
document.execCommand('copy');
|
document.execCommand('copy');
|
||||||
document.body.removeChild(el);
|
document.body.removeChild(el);
|
||||||
|
if (selected) {
|
||||||
|
document.getSelection().removeAllRanges();
|
||||||
|
document.getSelection().addRange(selected);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user