Jekyll uses div.highlighter-rouge as the wrapper around any codeblock sections.
For each block, we create a button with an event.
First add the Javascript block
<script>
document.addEventListener("DOMContentLoaded", function() {
document.querySelectorAll("div.highlighter-rouge").forEach(function(block) {
var code = block.innerText;
var btn = document.createElement("button");
btn.innerHTML = "COPY";
btn.className = "code-copy-btn";
btn.style.position = "absolute";
btn.style.top = "8px";
btn.style.right = "8px";
btn.onclick = function() {
navigator.clipboard.writeText(code);
btn.innerHTML = "COPIED";
btn.classList.add("copied");
setTimeout(function() {
btn.innerHTML = "COPY";
btn.classList.remove("copied");
}, 2000);
};
block.style.position = "relative";
block.appendChild(btn);
});
});
</script>
NEXT we will add some helpful CSS which places your button in the top-right corner of your code-block.
<style media="screen">
div.highlighter-rouge {
position: relative;
}
div.highlighter-rouge button {
position: absolute;
top: 2.3rem;
left: 10px;
}
</style>