DEV Community

loading...

Is it possible to write this code in a simpler way?

Nadine M. Thêry
At my 30s I found out that there was a developer inside a Political Science Graduated. I've been COO an CMO for 4 years but I decided to persue my dream and become a Front-end developer:)
・1 min read

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. :)

Click to check the Codepen

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");
}

Discussion (5)

Collapse
niorad profile image
Antonio Radovcic • Edited

yes

function switchBulb(){
  var element= document.getElementById("bulb");
  element.classList.toggle("on");
  element.classList.toggle("off");
}

It's a bit hacky though, since if you ever have either both "off"/"on" classes, or none, it won't work. as long as initially there's only off OR on, it should be fine.

In nowadays hyper-engineered world, you would keep the state of the bulb in a JS-variable, switch that and update the rendered HTML after the fact.

For prod I'd probably leave JS out and turn the bulb into a checkbox and style the :checked state. (see the clickable lids on devlids.com for example)

Collapse
nanythery profile image
Nadine M. Thêry Author

Really!! Thanks a lot.

Collapse
nickytonline profile image
Nick Taylor (he/him) • Edited

You actually don't need an off class. That can just be part of the bulb class. Then all you need to do is toggle the on class. Here's a fork of your codepen with the changes. I also, for fun, change the switch text based on the status.

If something isn't clear let me know and I can clarify.

Also, if you want to embed a codepen you can do the following for example:

{%codepen https://codepen.io/nickytonline/pen/OeLVqg %}

Collapse
nanythery profile image
Nadine M. Thêry Author

Absolutely right. Thanks for your help and advice :)

Collapse
n8chz profile image
Lorraine Lee

It would probably be an abuse of HTML, but I would write the bulb element as a <checkbox> element and use CSS magick to make my checkbox look like a light bulb.