DEV Community

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

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

Really!! Thanks a lot.