Copies a string to the clipboard.
Only works as a result of user action (i.e. inside a click
event listener).
<textarea>
element, fill it with the supplied data and add it to the HTML document.Selection.getRangeAt()
to store the selected range (if any).Document.execCommand()
to copy to the clipboard.<textarea>
element from the HTML document.Selection.addRange()
to recover the original selected range (if any).const copyToClipboard = str => {
const el = document.createElement('textarea');
el.value = str;
el.setAttribute('readonly', '');
el.style.position = 'absolute';
el.style.left = '-9999px';
document.body.appendChild(el);
const selected =
document.getSelection().rangeCount > 0
? document.getSelection().getRangeAt(0)
: false;
el.select();
document.execCommand('copy');
document.body.removeChild(el);
if (selected) {
document.getSelection().removeAllRanges();
document.getSelection().addRange(selected);
}
};
copyToClipboard('Lorem ipsum'); // 'Lorem ipsum' copied to clipboard.
JavaScript, Browser
Copies a string to the clipboard, returning a promise that resolves when the clipboard's contents have been updated.
JavaScript, Browser
Runs the callback whenever the user clicks outside of the specified element.
JavaScript, Browser
Adds an event listener to an element that will only run the callback the first time the event is triggered.