Add Copy to Clipboard Buttons to Code Blocks in Hugo
Many websites have plug-ins for Copy to Clipboard Buttons, but after consulting many documents. I didn’t like the page layout and it’s very difficult to adjust. I checked some foreign websites and ended up sharing the code I found. I’ve tweaked the code here and there.
See below an example of what it will look like:
Add a Copy to Clipboard
A block of code without syntax highlighting has the same structure, but nothing around <div class=highlight>
. To account for both cases, I chose to put a child element <pre>
below the <code>
element.
copy-to-clipboard.css
:
.highlight {
position: relative;
}
.highlight pre {
padding-right: 75px;
background-color:#312828 !important;
}
.highlight-copy-btn {
position: absolute;
bottom: 1px;
right: 3px;
border: 0;
border-radius: 2px;
padding: 1px;
font-size: 0.8em;
line-height: 1.8;
color: rgb(17, 13, 13);
background-color: rgb(22, 21, 21);
min-width: 55px;
text-align: center;
}
.highlight-copy-btn:hover {
background-color: rgb(33, 32, 32);
}
Interacting with the clipboard
Now that the button is available, the next step is to use JavaScript to copy the code to the clipboard.
Code: copy-to-clipboard.js
(function() {
'use strict';
if(!document.queryCommandSupported('copy')) {
return;
}
function flashCopyMessage(el, msg) {
el.textContent = msg;
setTimeout(function() {
el.textContent = "Copy Text Block";
}, 1000);
}
function selectText(node) {
var selection = window.getSelection();
var range = document.createRange();
range.selectNodeContents(node);
selection.removeAllRanges();
selection.addRange(range);
return selection;
}
function addCopyButton(containerEl) {
var copyBtn = document.createElement("button");
copyBtn.className = "highlight-copy-btn";
copyBtn.textContent = "Copy Text Block";
var codeEl = containerEl.firstElementChild;
copyBtn.addEventListener('click', function() {
try {
var selection = selectText(codeEl);
document.execCommand('copy');
selection.removeAllRanges();
flashCopyMessage(copyBtn, 'Copied!')
} catch(e) {
console && console.log(e);
flashCopyMessage(copyBtn, 'Failed :\'(')
}
});
containerEl.appendChild(copyBtn);
}
// Add copy button to code blocks
var highlightBlocks = document.getElementsByClassName('highlight');
Array.prototype.forEach.call(highlightBlocks, addCopyButton);
})();
Edit theme
Put copy-to-clipboard.css
and in the en directory copy-to-clipboard.js
respectively static/css
static/js
Then refer to these two files on the page
- Edit
config.toml
and add custom css
custom_css = ["/css/copy-to-clipboard.css"]
Then Run Hugo
hugo server
The final result is as follows:
Share on: