journal/templates/js/code_copy.js
Isaac Mills 7f6548e805
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
Add code copy button
2024-04-23 08:44:25 -04:00

32 lines
824 B
JavaScript

const copyButtonLabel = "Copy Code";
// use a class selector if available
if (navigator.clipboard) {
let blocks = document.querySelectorAll("pre");
blocks.forEach((block) => {
// only add button if browser supports Clipboard API
let button = document.createElement("button");
button.innerText = copyButtonLabel;
block.parentNode.insertBefore(button, block);
button.addEventListener("click", async (event) => {
await copyCode(block, event.target);
});
});
}
async function copyCode(block, button) {
let code = block.querySelector("code");
let text = code.innerText;
await navigator.clipboard.writeText(text);
// visual feedback that task is completed
button.innerText = "Code Copied";
setTimeout(() => {
button.innerText = copyButtonLabel;
}, 700);
}