copy-code-block.js 988 B

123456789101112131415161718192021222324252627282930313233343536
  1. /*
  2. * Every codeblock has "pre > code" structure, some highlighted codeblocks have
  3. * "div.highlight > pre.chroma > code" structure. So, use the simple CSS selector
  4. * to query all codeblocks.
  5. */
  6. document.addEventListener("DOMContentLoaded",
  7. () => {
  8. var codeblocks = document.querySelectorAll(".single .content pre code");
  9. console.log("codeblocks length:", codeblocks.length);
  10. codeblocks.forEach(
  11. (codeblock) => {
  12. let elementPre = codeblock.parentElement;
  13. let button = document.createElement("div");
  14. button.classList.add("copyCodeButton");
  15. button.innerHTML = "copy";
  16. button.addEventListener("click",
  17. () => {
  18. navigator.clipboard.writeText(codeblock.textContent);
  19. button.innerHTML = "copied!";
  20. setTimeout(
  21. () => { button.innerHTML = "copy"; },
  22. 1000
  23. );
  24. }
  25. );
  26. elementPre.appendChild(button);
  27. }
  28. );
  29. }
  30. );