Skip to content

Instantly share code, notes, and snippets.

@richarddewit
Last active December 14, 2018 09:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save richarddewit/3700e21c4103d60d33fafb7eabb44646 to your computer and use it in GitHub Desktop.
Save richarddewit/3700e21c4103d60d33fafb7eabb44646 to your computer and use it in GitHub Desktop.
Copy-to-clipboard button - https://codepen.io/richarddewit/pen/jQZoyb
var copyBtn = document.querySelector('.js-copy-button');
var originalContent = copyBtn.innerHTML;
copyBtn.addEventListener('click', function(event) {
var copyContents = document.querySelector('.js-copy-contents');
// Clear selection first
window.getSelection().removeAllRanges();
// Select the contents
var range = document.createRange();
range.selectNode(copyContents);
window.getSelection().addRange(range);
try {
// Do the copy
document.execCommand('copy');
// Flash success message inside button
copyBtn.disabled = true;
copyBtn.innerHTML = 'Copied!';
setTimeout(function() {
// And return to original state
copyBtn.disabled = false;
copyBtn.innerHTML = originalContent;
}, 1500);
} catch(err) {
console.log('Oops, unable to copy');
}
// Remove the selections - NOTE: Should use
// removeRange(range) when it is supported
window.getSelection().removeAllRanges();
});
<div class="well js-copy-contents">
https://example.com/invitation?key=7a8f6s78afs8a7ft678t22nin22j
</div>
<button class="btn btn-primary js-copy-button">
Copy invitation link
</button>
@richarddewit
Copy link
Author

richarddewit commented Nov 22, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment