Skip to content

Instantly share code, notes, and snippets.

@marco-souza
Created September 10, 2019 21:49
Show Gist options
  • Save marco-souza/23d62700a3e5037e3e77b99e6b914ba7 to your computer and use it in GitHub Desktop.
Save marco-souza/23d62700a3e5037e3e77b99e6b914ba7 to your computer and use it in GitHub Desktop.
Function to copy text to clipboard in JS Vanilla
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