summaryrefslogtreecommitdiff
path: root/static/js/copy-code.js
blob: 2de3cda529ae9f908651ef76c7cf924ee8e9fc57 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
document.addEventListener("DOMContentLoaded", function () {
  const codeBlocks = document.querySelectorAll("pre");

  codeBlocks.forEach((codeBlock) => {
    if (codeBlock.className == "mermaid") return;
    const copyButton = document.createElement("button");
    copyButton.className = "copy-code-button";
    copyButton.textContent = "copy";

    // Insert the button inside the <pre> block
    codeBlock.appendChild(copyButton);

    copyButton.addEventListener("click", function () {
      const code = codeBlock.querySelector("code");
      // Get the code content
      const textToCopy = code.textContent || code.innerText;

      // Use the Clipboard API to copy the text
      navigator.clipboard
        .writeText(textToCopy)
        .then(() => {
          // Change button text to "Copied"
          copyButton.textContent = "copied";

          setTimeout(() => {
            copyButton.textContent = "copy";
          }, 2000); // Reset the button text after 2 seconds
        })
        .catch((err) => {
          console.error("Unable to copy text:", err);
        });
    });
  });
});