-
I created a javascript function for add a import htmx from 'htmx.org';
window.htmx = htmx;
function copyCodeButton () {
const copyButtonLabel = "Copy Code";
// use a class selector if available
let blocks = document.querySelectorAll("pre.b");
blocks.forEach((block) => {
// only add button if browser supports Clipboard API
if (navigator.clipboard) {
let button = document.createElement("button");
button.className = "copyBtn";
button.innerText = copyButtonLabel;
block.prepend(button);
button.addEventListener("click", async () => {
await copyCode(block, button);
});
}
});
async function copyCode(block, button) {
let code = block.querySelector("code");
let text = code.innerText;
await navigator.clipboard.writeText(text);
button.innerText = "Code Copied";
setTimeout(() => {
button.innerText = copyButtonLabel;
}, 1500);
}
}
function init () {
copyCodeButton();
}
htmx.onLoad(init); it works if not enable But, when use mouse click same page again(hx-boost enabled), i get 3 duplicate buttons (even current page only one <pre> tag exists), as show in following screenshot. Any idea for how to fixed that? Thanks in advance! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 7 replies
-
Hey, I see your buttons don't have a Could you try adding |
Beta Was this translation helpful? Give feedback.
Oh right,
htmx:load
can be confusing because of its name, but as its documentation states:So for each node added by htmx in the DOM, including during the page's lifetime, your function would execute and instanciate a new button.
If you want to run this logic only on the first page load or when the body content changes (i.e. a boosted request that replaces the page content and acts as if you changed page), I think you could check if the
event.detail.elt
is the body itself or not (if it isn't, ignore it)It seems you're not using any htmx feature in your JS code though, so you might even want to consider not relying …