Is it possible to write this code in a simpler way?
Nadine M. Thêry
Posted on June 9, 2019
I just made this piece of code in order to light the bulb and switch it off.
The bulb has an "on" class. And an "off" class. So, in order to be in a certain status there must be at least one class activated for the #bulb.
I first thought about just toggling the "on" class and leaving the off behind, but didn't work for two reasons:
1) the classList.toggle function only admits one class at the time. So the "off" class doesn't dissapear if the "on" is included at the time.
2) both classes cannot co-exist at the time since they are formatting the same object. So what I got was an off bulb with yellow shadow.
So I came up with this conditional, to make it dissapear.
I would love to know other ways possible to make it simpler. Any suggestions?
Be gentle with me, this is my very first working code in JavaScript. :)
This is the code:
function switchBulb(){
var element= document.getElementById("bulb");
var status = element.classList.toggle("on");
if (status !== false){
var status = element.classList.remove("off");
} else
var status = element.classList.add("off");
}
Posted on June 9, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.