Skip to content

Instantly share code, notes, and snippets.

@danfoust
Created February 28, 2019 19:12
Show Gist options
  • Save danfoust/1812743328fda300976dba6c64d67122 to your computer and use it in GitHub Desktop.
Save danfoust/1812743328fda300976dba6c64d67122 to your computer and use it in GitHub Desktop.
Simple Vanilla js approach for copying text of data attribute on click
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