Last active
November 29, 2017 13:44
-
-
Save christierney402/5e16cbf5c90f841cee8c to your computer and use it in GitHub Desktop.
HTML5 Copy to Clipboard
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
// Remove copy button if copy to clipboard method is not allowed | |
// Note: Button detection is broken before Chrome 48 | |
var copyBtn = document.querySelector('.copyToClip'); | |
if (copyBtn !== null) { | |
if( !document.queryCommandSupported('copy') ) { | |
copyBtn.parentNode.removeChild(copyBtn); | |
}; | |
// When .copyBtn is clicked, copy .copyToClip content to user's clipboard | |
copyBtn.addEventListener('click', function(event) { | |
// Select the text | |
var copyContent = document.querySelector('.copyToClipContent'); | |
var range = document.createRange(); | |
range.selectNode(copyContent); | |
window.getSelection().addRange(range); | |
// Now that we've selected the text, execute the copy command | |
document.execCommand('copy'); | |
// Remove the selections | |
window.getSelection().removeAllRanges(); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment