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
CodePudding user response:
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)
})
CodePudding user response:
The switch has an input inside of it. I think this causes the click event to bubble up to the switch element and causes the toggle to fire twice. Try adding the following so that only one click event is triggered:
document.querySelector(".switch > input").addEventListener("click", (e) => {
e.stopPropagation();
})
Alternatively, attach the event to the input:
const switchButtonInput = document.querySelector(".switch > input")
switchButtonInput.addEventListener("click", () => {
document.querySelector("body").classList.toggle("dark")
});
body.dark { background-color: grey; }
.switch { padding: 10px; border: 1px solid black; }
.switch > input { display: none; }
<label >
<input type="checkbox">
toggle
</label>
CodePudding user response:
Your code is working fine. I checking the check is check, then I making a decision. If the check is checked turn off the light with adding class to the body, if it is not checked remove the class dark...
const switchButton = document.querySelector(".switch")
const body = document.querySelector("body");
switchButton.addEventListener("click", () => {
switchButton.checked ? body.classList.add("dark") : body.classList.remove("dark");
})
body.dark {background:black;}
body {background:white;}
<input type="checkbox" >Toggle dark</ button>