Created
February 28, 2019 19:12
-
-
Save danfoust/1812743328fda300976dba6c64d67122 to your computer and use it in GitHub Desktop.
Simple Vanilla js approach for copying text of data attribute on click
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
document.querySelectorAll('.copy-text').forEach(function(elem) { | |
elem.addEventListener('click', function() { | |
var copyText = this.getAttribute('data-copyText'); | |
copyToClipboard(copyText); | |
}); | |
}); | |
function copyToClipboard(text) { | |
var selected = false; | |
var el = document.createElement('textarea'); | |
el.value = text; | |
el.setAttribute('readonly', ''); | |
el.style.position = 'absolute'; | |
el.style.left = '-9999px'; | |
document.body.appendChild(el); | |
if (document.getSelection().rangeCount > 0) { | |
selected = document.getSelection().getRangeAt(0) | |
} | |
el.select(); | |
document.execCommand('copy'); | |
document.body.removeChild(el); | |
if (selected) { | |
document.getSelection().removeAllRanges(); | |
document.getSelection().addRange(selected); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment