Created
October 9, 2020 12:43
-
-
Save sudarshann/4213436cb745b14a95529c4d60b0776b to your computer and use it in GitHub Desktop.
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
function copyToClipboard(textToCopy) { | |
var textArea; | |
function isOS() { | |
//can use a better detection logic here | |
return navigator.userAgent.match(/ipad|iphone/i); | |
} | |
function createTextArea(text) { | |
textArea = document.createElement('textArea'); | |
textArea.readOnly = true; | |
textArea.contentEditable = true; | |
textArea.value = text; | |
document.body.appendChild(textArea); | |
} | |
function selectText() { | |
var range, selection; | |
if (isOS()) { | |
range = document.createRange(); | |
range.selectNodeContents(textArea); | |
selection = window.getSelection(); | |
selection.removeAllRanges(); | |
selection.addRange(range); | |
textArea.setSelectionRange(0, 999999); | |
} else { | |
textArea.select(); | |
} | |
} | |
function copyTo() { | |
document.execCommand('copy'); | |
document.body.removeChild(textArea); | |
} | |
createTextArea(textToCopy); | |
selectText(); | |
copyTo(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment