Skip to content

Instantly share code, notes, and snippets.

@UnderlineWords
Created October 1, 2021 20:08
Show Gist options
  • Save UnderlineWords/e9f49a09588771472fb418d305e54141 to your computer and use it in GitHub Desktop.
Save UnderlineWords/e9f49a09588771472fb418d305e54141 to your computer and use it in GitHub Desktop.
Copy to clipboard with Pure JS
/**
* @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