Last active
November 10, 2020 19:09
-
-
Save stefcameron/ada36969fee9fc0319ae0ccd94fc7a3a to your computer and use it in GitHub Desktop.
Copy text to clipboard
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Copy the specified string to the clipboard. | |
* @param {string} text The text to copy. | |
* @returns {boolean} `true` if the copy succeeded; `false` if an | |
* error occurred copying the text to the clipboard. | |
*/ | |
export const copyToClipboard = (text) => { | |
try { | |
// NOTE: a field is required to execute the document's 'copy' command; | |
// make sure the first appears offscreen without affecting layout | |
// @see https://hackernoon.com/copying-text-to-clipboard-with-javascript-df4d4988697f | |
const el = document.createElement('textarea'); | |
el.setAttribute('readonly', ''); | |
el.style.position = 'absolute'; | |
el.style.left = '-9999px'; | |
document.body.appendChild(el); | |
el.value = text; | |
el.select(); | |
document.execCommand('copy'); | |
document.body.removeChild(el); | |
} catch (err) { | |
return false; | |
} | |
return true; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment