// Add copy buttons to all code blocks document.addEventListener("DOMContentLoaded", function () { // Find all
elements that contain
const codeBlocks = document.querySelectorAll("pre code");
codeBlocks.forEach((codeBlock) => {
const pre = codeBlock.parentElement;
// Skip if data-lang is "nocopy"
if (codeBlock.dataset.lang === "nocopy") {
return;
}
// Create wrapper for positioning
const wrapper = document.createElement("div");
wrapper.style.position = "relative";
// Wrap the pre element
pre.parentNode.insertBefore(wrapper, pre);
wrapper.appendChild(pre);
// Create copy button
const copyButton = document.createElement("button");
copyButton.className = "code-copy-btn";
copyButton.innerHTML = `
`;
copyButton.setAttribute("aria-label", "Copy code to clipboard");
// Add click handler
copyButton.addEventListener("click", async () => {
const code = codeBlock.textContent;
try {
await navigator.clipboard.writeText(code);
// Show success feedback
copyButton.classList.add("copied");
// Reset after 2 seconds
setTimeout(() => {
copyButton.classList.remove("copied");
}, 2000);
} catch (err) {
console.error("Failed to copy code:", err);
// Fallback for older browsers
const textArea = document.createElement("textarea");
textArea.value = code;
textArea.style.position = "fixed";
textArea.style.opacity = "0";
document.body.appendChild(textArea);
textArea.select();
try {
document.execCommand("copy");
copyButton.classList.add("copied");
setTimeout(() => {
copyButton.classList.remove("copied");
}, 2000);
} catch (err2) {
console.error("Fallback copy failed:", err2);
}
document.body.removeChild(textArea);
}
});
wrapper.appendChild(copyButton);
});
});