From 80f257003f83e2ca38a4843cf7593d22fef68108 Mon Sep 17 00:00:00 2001 From: Oliver Ladner Date: Wed, 1 Jul 2026 11:37:13 +0200 Subject: [PATCH] feat: copy code block button --- static/js/copy-code.js | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 static/js/copy-code.js diff --git a/static/js/copy-code.js b/static/js/copy-code.js new file mode 100644 index 00000000..42a03831 --- /dev/null +++ b/static/js/copy-code.js @@ -0,0 +1,27 @@ +// NOTE: Pelican's fenced_code puts language-* on , not
,
+// so we select the  elements and walk up to the 
.
+const codeBlocks = document.querySelectorAll('code[class*="language-"]');
+
+console.log("copy-code.js loaded, found:", codeBlocks.length);
+
+codeBlocks.forEach((code) => {
+  const pre = code.closest("pre");
+  if (!pre) return;
+
+  const button = document.createElement("button");
+  button.className = "copy-to-clipboard-button";
+  button.type = "button";
+  button.textContent = "Copy";
+
+  button.addEventListener("click", async () => {
+    try {
+      await navigator.clipboard.writeText(code.innerText);
+      button.textContent = "Copied";
+    } catch {
+      button.textContent = "Failed";
+    }
+    setTimeout(() => (button.textContent = "Copy"), 1500);
+  });
+
+  pre.appendChild(button);
+});