I'm trying to do a dark mode button for my website. my idea is to use an event on click to change the side of my button switch from left to the right and right to the left. it works on my first click, it switches from left to the right (from off to on). But when I try to switch it back again nothing happens. Here's my code
const buttonmode = document.querySelector("#darkmode");
const switchmode = document.querySelector("#darkswitch");
buttonmode.addEventListener("click",(e) =>{
e.preventDefault();
if(switchmode.style.float="left"){
switchmode.style.float="right";
}
else if(switchmode.style.float="right"){
switchmode.style.float="left";
}
});
heres my css
button span{
display: block;
background: #999;
height: 26px;
width: 26px;
border-radius: 50%;
margin-left: 2px;
float: left;
}
CodePudding user response:
Your problem is you define switchmode
variable outside of the function and re-use it in your function. Whenever DOM gets updated, your variable is not updated as you expected. You should get switchmode
again for the next updates in the function.
You also have a small problem here
if(switchmode.style.float="left")
It should be ===
instead of =
for if-else condition.
const buttonmode = document.querySelector("#darkmode");
buttonmode.addEventListener("click",(e) =>{
e.preventDefault();
const switchmode = document.querySelector("#darkswitch"); //move it here
if(switchmode.style.float==="left"){
switchmode.style.float="right";
}
else if(switchmode.style.float==="right"){
switchmode.style.float="left";
}
});
CodePudding user response:
In your conditional statement, in order to check what the current float
value is you need to use ==
not just =
const buttonmode = document.querySelector("#darkmode");
const switchmode = document.querySelector("#darkswitch");
buttonmode.addEventListener("click",(e) =>{
e.preventDefault();
if(switchmode.style.float == "left") {
switchmode.style.float="right";
} else {
switchmode.style.float="left";
}
});
#darkswitch {
width:50px;
height:50px;
background:black;
}
<button id="darkmode">Dark Mode</button>
<div id="darkswitch"></div>
CodePudding user response:
I would suggest using classList.toggle
const themeSwitcher = document.getElementById("themeSwitcher");
themeSwitcher.addEventListener("click", function () {
this.classList.toggle("dark");
});
#themeSwitcher {
width: 70px;
height: 30px;
border-radius: 50px;
background-color: #ffffff;
border: 2px solid #252525;
}
#toggler {
float: left;
width: 30px;
height: 30px;
background-color: #000000;
border-radius: 50%;
}
.dark #toggler {
float: right;
}
<div id="themeSwitcher">
<div id="toggler"></div>
</div>