Home > front end >  Simplest way to toggle functionality in vanilla JS
Simplest way to toggle functionality in vanilla JS

Time:11-26

Anyways I’m trying to make a lightbulb. It’s just a circle, I have an onclick event on a button, and the event function toggled a class, changing the color. But I want the text in the button to toggle as well when that class is activated.

I finally made it work as I was writing this question. But it still isn’t working how I want it. I only want to have one if statement.

I only want to solve it this specific way, by checking if a class is activated, and if yes, then change the text content of the button, if not, then leave it how it is.

let bulb = document.getElementById("light");
let lightSwitch = document.getElementById("switch");

function activity(event) {
  bulb.classList.toggle("lightOn");

  if (bulb.classList.contains("lightOn")) {
    lightSwitch.textContent = "OFF";
  } else if (bulb.classList.contains("lightOff")) {

    lightSwitch.textContent = "ON";
  }

}
.lightOn {
  background: yellow;
}
<div id="light" ></div>
<button id="switch" onclick="activity()">ON</button>

How can I write it with only one if statement, Also, is there a way easier than this? Just vanilla not jQuery.

CodePudding user response:

like this?

...

function activity(event) {
   bulb.classList.toggle("lightOn");
   lightSwitch.textContent = bulb.classList.contains("lightOn") ? "OFF" : "ON";
}

...

CodePudding user response:

Your code can be simplified by extracting the bulb-specific default styles into a light class, then only toggle a new lightOn class. The default styles describe what to show if the bulb is off, but you can override those styles with !important in the lightOn class. Just like this:

let bulb = document.getElementById("light");
let lightSwitch = document.getElementById("switch");

lightSwitch.addEventListener('click', function() {
  bulb.classList.toggle('lightOn');
  lightSwitch.textContent = bulb.classList.contains("lightOn") ? "OFF" : "ON";
});
.light {
  width: 100px;
  height: 100px;
  border-radius: 100%;
  background: gray;
}

.lightOn {
  background: yellow !important;
}
<div id="light" ></div>
<button id="switch">ON</button>

You can also shorten your if-statement into a ternary expression, which is a better choice for this situation because only one value changes.

  • Related