Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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/

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

You can check the checkbox state

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

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading