Last active
March 21, 2019 02:17
-
-
Save dgraham/cda03d4a4a528d2b4d17 to your computer and use it in GitHub Desktop.
Copy attribute value, form input, or element text to the clipboard.
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
(function() { | |
function createNode(text) { | |
var node = document.createElement('pre'); | |
node.style.width = '1px'; | |
node.style.height = '1px'; | |
node.style.position = 'fixed'; | |
node.style.top = '5px'; | |
node.textContent = text; | |
return node; | |
} | |
function copyNode(node) { | |
var selection = getSelection(); | |
selection.removeAllRanges(); | |
var range = document.createRange(); | |
range.selectNodeContents(node); | |
selection.addRange(range); | |
document.execCommand('copy'); | |
selection.removeAllRanges(); | |
} | |
function copyText(text) { | |
var node = createNode(text); | |
document.body.appendChild(node); | |
copyNode(node); | |
document.body.removeChild(node); | |
} | |
function copyInput(node) { | |
node.select(); | |
document.execCommand('copy'); | |
getSelection().removeAllRanges(); | |
} | |
function isFormInput(element) { | |
return element.nodeName === 'INPUT' || element.nodeName === 'TEXTAREA'; | |
} | |
$(document).on('click', '.js-copy-button', function() { | |
var text; | |
if (text = this.getAttribute('data-clipboard-text')) { | |
copyText(text); | |
} else { | |
var container = this.closest('.js-copy-container'); | |
var content = container.querySelector('.js-copy-target'); | |
if (isFormInput(content)) { | |
if (content.type === 'hidden') { | |
copyText(content.value); | |
} else { | |
copyInput(content); | |
} | |
} else { | |
copyNode(content); | |
} | |
} | |
this.blur(); | |
}); | |
}).call(this); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This clipboard behavior is now available as a custom element in github/clipboard-copy-element.