I want to try the dark mode switch for laptop and mobile. So, I used two toggles and also used local storage. I have a problem. In two toggles, only work first toggle for dark mode. I want to run two toggle switches at the same time. When I want to switch on, another toggle also switches on automatically.
HTML
<li><a id="sidebar-a">Darkmode
<input type="checkbox" id="switch"><label class="label2" for="switch">Toggle</label>
<li><a id="sidebar-a">Darkmode
<input type="checkbox" id="switch2"><label class="label6" for="switch2">Toggle</label>
CSS
body.light {
--body-back: #F7F7F8;
--h1-color: #42493e;
--a-color:#39393A;
--setting-tool:#696969;
--quick-bar:#E5E5E5;
--quick-bar2:#dee4e7;
}
body.dark{
--body-back:#0e0e10;
--h1-color:orange;
--a-color:#dfdfe1;
--quick-bar:#464649;
--quick-bar2:#37474f;
}
body{
background: var(--body-back);
}
input[type="checkbox"]{
height: 0;
width: 0;
visibility: hidden;
}
.label2{
enter code here
cursor: pointer;
text-indent: -9999px;
width: 46px;
height: 23px;
background: #c4c4c4;
display: block;
border-radius: 100px;
position: absolute;
margin-left: 124px;
margin-top: -37px;
}
.label2::after{
content: "";
position: absolute;
top: 2.4px;
left: 2.5px;
width: 20px;
height: 20px;
background:#34393f ;
border-radius: 90px;
transition: 0.3s;
}
input:checked + .label2{
background: black;
}
input:checked + .label2::after{
left: calc(100% - 2.5px);
transform: translateX(-100%);
}
input:checked + .label6{
background: black;
}
input:checked + .label6::after{
left: calc(100% - 2.5px);
transform: translateX(-100%);
}
.label6{
cursor: pointer;
text-indent: -9999px;
width: 46px;
height: 23px;
background: #c4c4c4;
display: block;
border-radius: 100px;
position: absolute;
margin-left: 124px;
margin-top: -37px;
}
.label6::after{
content: "";
position: absolute;
top: 2.4px;
left: 2.5px;
width: 20px;
height: 20px;
background:#34393f ;
border-radius: 90px;
transition: 0.3s;
}
const chkToggle = document.querySelector("#switch")
const theme = localStorage.getItem("theme")
document.body.classList.toggle(theme === "dark" ? "dark" : "light")
if (theme == "dark"){
chkToggle.checked = true
}
else {
chkToggle.checked = false
}
chkToggle.addEventListener("change", function (e){
e.preventDefault()
if (this.checked) {
document.body.classList.add("dark")
document.body.classList.remove("light")
localStorage.setItem("theme", "dark")
console.log("dark mode");
}
else{
document.body.classList.add("light")
document.body.classList.remove("dark")
localStorage.setItem("theme", "light")
console.log("light mode");
}
})
It doesn’t work