Skip to content

Instantly share code, notes, and snippets.

@Lokua
Created February 5, 2017 19:15
Show Gist options
  • Save Lokua/2424a023896f44e098968f9c49aa92b6 to your computer and use it in GitHub Desktop.
Save Lokua/2424a023896f44e098968f9c49aa92b6 to your computer and use it in GitHub Desktop.
browser programmatic text copy
export default function copy(text) {
const textArea = document.createElement(`textarea`)
textArea.value = text
textArea.style.width = `2em`
textArea.style.height = `2em`
textArea.style.background = `transparent`
document.body.appendChild(textArea)
textArea.select()
const success = document.execCommand(`copy`)
document.body.removeChild(textArea)
if (success) {
const div = document.createElement(`div`)
div.textContent = `Copied!`
div.style.position = `fixed`
div.style.top = `2em`
div.style.width = `100vw`
div.style.color = `blue`
div.style.backgroundColor = `white`
div.style.textAlign = `center`
div.style.fontSize = `3em`
div.style.zIndex = 3
document.body.appendChild(div)
setTimeout(() => document.body.removeChild(div), 888)
} else {
alert(`Failed to copy :(`)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment