Skip to content

Instantly share code, notes, and snippets.

@dguo
Last active March 24, 2019 03:32
Show Gist options
  • Save dguo/2644db7b3c2c059cca869019b80d65b2 to your computer and use it in GitHub Desktop.
Save dguo/2644db7b3c2c059cca869019b80d65b2 to your computer and use it in GitHub Desktop.
blog - How to Add Copy to Clipboard Buttons to Code Blocks in Hugo - add-copy-buttons
function addCopyButtons(clipboard) {
document.querySelectorAll('pre > code').forEach(function (codeBlock) {
var button = document.createElement('button');
button.className = 'copy-code-button';
button.type = 'button';
button.innerText = 'Copy';
button.addEventListener('click', function () {
clipboard.writeText(codeBlock.innerText).then(function () {
/* Chrome doesn't seem to blur automatically,
leaving the button in a focused state. */
button.blur();
button.innerText = 'Copied!';
setTimeout(function () {
button.innerText = 'Copy';
}, 2000);
}, function (error) {
button.innerText = 'Error';
});
});
var pre = codeBlock.parentNode;
if (pre.parentNode.classList.contains('highlight')) {
var highlight = pre.parentNode;
highlight.parentNode.insertBefore(button, highlight);
} else {
pre.parentNode.insertBefore(button, pre);
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment