Add optional copy code button!

This commit is contained in:
David Lapshin
2024-05-09 22:01:25 +03:00
parent 398fb7ebfd
commit 3f87d78b33
4 changed files with 95 additions and 1 deletions

31
static/copy-button.js Normal file
View File

@ -0,0 +1,31 @@
// Based on https://www.roboleary.net/2022/01/13/copy-code-to-clipboard-blog.html
document.addEventListener("DOMContentLoaded", function () {
let blocks = document.querySelectorAll("pre[class^='language-']");
blocks.forEach((block) => {
if (navigator.clipboard) {
let button = document.createElement("button");
let icon = document.createElement("i");
button.appendChild(icon);
block.appendChild(button);
button.addEventListener("click", async () => {
await copyCode(block, button);
});
}
});
async function copyCode(block, button) {
let code = block.querySelector("code");
let text = code.innerText;
await navigator.clipboard.writeText(text);
button.classList.add("active");
setTimeout(() => {
button.classList.remove("active");
}, 800);
}
});