Last active
December 14, 2018 09:32
-
-
Save richarddewit/3700e21c4103d60d33fafb7eabb44646 to your computer and use it in GitHub Desktop.
Copy-to-clipboard button - https://codepen.io/richarddewit/pen/jQZoyb
This file contains 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
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(); | |
}); |
This file contains 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
<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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
CodePen: https://codepen.io/richarddewit/pen/jQZoyb