'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 1:[1]
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)
})
Solution 2:[2]
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 class="switch">
<input type="checkbox">
toggle
</label>
Solution 3:[3]
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" class="switch dark">Toggle dark</ button>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | |
| Solution 3 |
