I have opened a different post with some small debugging help here because in the previous one some different issue with different logic was being discussed.
I have movd here from mutation observer to scroll, and all instances with new button are injected in DOM, but I used this counter in button data-counter="${currentCounter}"> it is not appending just printing "1" in all instances.
window.addEventListener("scroll", function () {
const toolBarDivs = document.querySelectorAll('div.tool-bar:not([data-sibling-injected])')
toolBarDivs.forEach(injectButton)
})
function createButtonHTML(counter) {
// simplified for testing
return `<button>Copaste ${counter}</button>`;
}
function injectButton(toolBarDiv) {
if (!toolBarDiv.dataset.buttonCounter) {
toolBarDiv.dataset.buttonCounter = 1
}
const currentCounter = toolBarDiv.dataset.buttonCounter
toolBarDiv.dataset.buttonCounter = parseInt(currentCounter) + 1
// has no effect on currentCounter so commented out
// const newDiv = document.createElement("div");
// newDiv.classList.add("css-175oi2r", "r-18u37iz", "r-1h0z5md", "r-13awgt0", "copy-paste-button")
// newDiv.innerHTML = createButtonHTML(currentCounter);
// const targetIndex = 3
// if (toolBarDiv.children.length > targetIndex) {
// toolBarDiv.insertBefore(newDiv, toolBarDiv.children[targetIndex])
// } else {
// toolBarDiv.appendChild(newDiv)
// }
toolBarDiv.dataset.siblingInjected = "true"
}
codepen You will need to right click and inspect the red boxes.
The result of my test is that dataset.buttonCounter will be set to 2 — That’s it. siblingInjected will prevent the toolbar from being selected a second time.
I would also add that the scroll event will fire hundreds and hundreds of times as you scroll, so this may not be the best solution — At least not without debounce.
To get to the bottom of this issue, it might be a good idea for you to create a simplified example. Much like I have tried to do.
Edit: I haven’t followed your other thread, so this maybe irrelevant now