Created
January 30, 2020 23:50
-
-
Save erikvullings/cd819861b56b5ad9d0cc6dc0fb17837c to your computer and use it in GitHub Desktop.
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
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); | |
} | |
}; | |
// Example | |
copyToClipboard('Lorem ipsum'); // 'Lorem ipsum' copied |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment