Skip to content

Instantly share code, notes, and snippets.

@dgraham
Last active March 21, 2019 02:17
Show Gist options
  • Save dgraham/cda03d4a4a528d2b4d17 to your computer and use it in GitHub Desktop.
Save dgraham/cda03d4a4a528d2b4d17 to your computer and use it in GitHub Desktop.
Copy attribute value, form input, or element text to the clipboard.
(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);
@dgraham
Copy link
Author

dgraham commented Apr 19, 2018

This clipboard behavior is now available as a custom element in github/clipboard-copy-element.

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