Search code examples
javascripttoggle

JS toggle adding just "class" without class name, add and remove working properly


I'm learning and trying add dark mode button to my site. I have working switch button and CSS. But when I want add to body class "dark" the toggle function isn't working properly. Function add and remove is working, but I don't want to solve it by "if".

const switchButton = document.querySelector(".switch")

switchButton.addEventListener("click", () => {
    document.querySelector("body").classList.toggle("dark")
})

When we replace toggle by add - it's working fine.

Here is live page: https://gearlistmaker.com/

And here is code: https://github.com/jankamon/GearListMaker


Solution

  • The click event is firing twice due to event bubbling

    You can check the checkbox state, which makes more sense and is safer

    https://jsfiddle.net/mplungjan/7hfv5ynb/

    switchButton.addEventListener("click", (e) => {
      document.querySelector("body").classList.toggle("dark", 
        switchButton.querySelector("input[type=checkbox]").checked)
    })