feat(copy-code): To allow user to copy contents within code block to clipboard

fix(ui): corrections told by tomfran

fix(ui): add more contrast to button.

fix(ui): loading js as deferred
This commit is contained in:
Arun Mathai 2025-01-14 17:27:28 +05:30
parent 2658baf36e
commit 6e5bc2f944
4 changed files with 82 additions and 28 deletions

33
static/js/copy-code.js Normal file
View file

@ -0,0 +1,33 @@
document.addEventListener("DOMContentLoaded", function () {
const codeBlocks = document.querySelectorAll("pre");
codeBlocks.forEach((codeBlock) => {
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);
});
});
});
});