Created
October 1, 2021 20:08
-
-
Save UnderlineWords/e9f49a09588771472fb418d305e54141 to your computer and use it in GitHub Desktop.
Copy to clipboard with Pure JS
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
/** | |
* @referenced https://stackoverflow.com/a/65996386/3299846 | |
* */ | |
function copyToClipboard(e) { | |
var copyText = document.getElementById(e); | |
// navigator clipboard api needs a secure context (https) | |
if (navigator.clipboard && window.isSecureContext) { | |
// navigator clipboard api method' | |
return navigator.clipboard.writeText(copyText.value); | |
} else { | |
// text area method | |
let textArea = document.createElement("textarea"); | |
textArea.value = copyText.value; | |
// make the textarea out of viewport | |
textArea.style.position = "fixed"; | |
textArea.style.left = "-999999px"; | |
textArea.style.top = "-999999px"; | |
document.body.appendChild(textArea); | |
textArea.focus(); | |
textArea.select(); | |
return new Promise((res, rej) => { | |
// here the magic happens | |
document.execCommand('copy') ? res() : rej(); | |
textArea.remove(); | |
alert('Kopyalandı'); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment