Hi, I am building a dark mode switcher. Therefore I implemented the dark-mode class in CSS. I toggle this via JS:
const button = document.getElementById("button");
button.addEventListener("click", toggler);
function toggler() {
var element = document.body;
document.body.classList.toggle("dark-mode");
}
Strange thing: It only works when running the chrome / firefox debugger in devtool (Clicken the source, setting a mouse click event and going step by step though the code. It does not work without devtools.) What am I missing?
Thank you very much
Hi @m3g4p0p thank you for your reply. But I don’t understand, why my code works while running debugging mode in devtools – but not without. Do you have an idea? Have a nice day
Hi @rpg_digital, thank you very much.
But placing the script tag above the closing body-tag does not help either. It’s like before: Opening debugger tool in devtools: Page switche to dark mode. without dev tool, no dark side of my page. Pls. see attached screenshot.
I would never get it, that this span nested inside the button would cause this trouble. I just watched it in the inspector and based on this the span only covers a tiny piece of the button.
It seems to be the label element that causes this because if you remove it then your code works OK. I’m guessing the label element simulates a click on the input resulting in effectively two clicks each time but I’ll leave that to the JS gurus to confirm
If you tweak the code to log the event target ((e) =>{ … console.log(e.target), you might get a better understanding of what’s happening.
The attachment to the #button element is tagging all of the sub-elements of #button with the trigger. When you click on the label, it’s clicking both the input and the span, so they both fire the event.
If you retarget your javascript to bind the click event to the element with id switch (for those that don’t want to dig: bind it to just the input element), you’ll find it works correctly.