Skip to content

Instantly share code, notes, and snippets.

@fidlerryan
Created January 4, 2016 15:21
Show Gist options
  • Save fidlerryan/e56c7b157d5ae07d4ce3 to your computer and use it in GitHub Desktop.
Save fidlerryan/e56c7b157d5ae07d4ce3 to your computer and use it in GitHub Desktop.
Copy to Clipboard from paragraph
document.addEventListener('DOMContentLoaded', function() {
var copybtn = document.getElementById('copybtn');
var authcode = document.getElementById('authcode');
copybtn.addEventListener('click', function() {
// select the authorization code text
var range = document.createRange();
range.selectNode(authcode);
window.getSelection().addRange(range);
try{
// with text selected, execute the copy command
var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';
if (msg == 'successful') copybtn.value = 'Copied!';
console.log('Copy authorization code command was ' + msg);
} catch(err) {
console.log('Oops, unable to copy');
}
// remove the selection
window.getSelection().removeAllRanges();
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment