From 95a3f2f83ce0e084c4dd055c01ed1a2c39a0918a Mon Sep 17 00:00:00 2001 From: Musselman Date: Mon, 8 Jul 2024 19:22:41 -0500 Subject: [PATCH] Add copy function --- assets/js/main.js | 34 +++++++++++++++++++++++++++++----- 1 file changed, 29 insertions(+), 5 deletions(-) diff --git a/assets/js/main.js b/assets/js/main.js index 79818c5..8d95134 100644 --- a/assets/js/main.js +++ b/assets/js/main.js @@ -1,5 +1,29 @@ -console.log("This site was generated by Hugo."); -function copyText() { - const text = document.getElementById("copyText").innerText; - navigator.clipboard.writeText(text); -} +document.addEventListener("DOMContentLoaded", function () { + const codeBlocks = document.querySelectorAll("pre, code"); + + codeBlocks.forEach(function (codeBlock) { + codeBlock.style.cursor = "pointer"; + codeBlock.title = "Click to copy"; + + codeBlock.addEventListener("click", function () { + const selection = window.getSelection(); + const range = document.createRange(); + range.selectNodeContents(codeBlock); + selection.removeAllRanges(); + selection.addRange(range); + + try { + document.execCommand("copy"); + const originalText = codeBlock.innerText; + codeBlock.innerText = "Copied!"; + setTimeout(function () { + codeBlock.innerText = originalText; + }, 1000); // Reset the text after 1 second + } catch (err) { + console.error("Unable to copy:", err); + } + + selection.removeAllRanges(); + }); + }); +});