Created
September 10, 2019 21:49
-
-
Save marco-souza/23d62700a3e5037e3e77b99e6b914ba7 to your computer and use it in GitHub Desktop.
Function to copy text to clipboard in JS Vanilla
This file contains hidden or 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
const copyToClipboard = (text, successCallback, errorCallback) => { | |
const textArea = document.createElement('textarea') | |
textArea.value = text | |
document.body.appendChild(textArea) | |
textArea.select() | |
try { | |
// Now that we've selected the anchor text, execute the copy command | |
document.execCommand('copy') | |
? successCallback() | |
: errorCallback() | |
} catch (error) { | |
errorCallback(error) | |
} | |
document.body.removeChild(textArea) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment