Skip to content

Instantly share code, notes, and snippets.

@christierney402
Last active November 29, 2017 13:44
Show Gist options
  • Save christierney402/5e16cbf5c90f841cee8c to your computer and use it in GitHub Desktop.
Save christierney402/5e16cbf5c90f841cee8c to your computer and use it in GitHub Desktop.
HTML5 Copy to Clipboard
// 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