Project 371: Count to 21

2. (Demo) Use conditional logic to toggle between green and gray

In this challenge, we're going to learn how to use conditional logic to get our code to make decisions. We want the circles to toggle between gray and green. So, if a circle is gray, it should turn green when clicked. And if not, it should turn back to gray. We'll need to use "if-else" statements as well as the "contains( )" JavaScript method.
Starting point link for this challenge

Your goal

Steps

1. Show different alerts depending on if the circle is green or gray

To make this step work, we're going to need to use "conditional logic". 

An "if-else" conditional logic statement has three parts:

  1. a condition, which is a test that is either true or false
  2. an "if" branch that holds code which runs if the condition is true
  3. an "else" branch that holds code which runs if the condition is false

It has the general structure of:

if (condition) {
  // some code
} else {
  // some code
}

Add an if-else statement to alert "turn off" if a circle has an "on" class and "turn on" if a circle doesn't have an "on" class.
document.addEventListener('click', function(event){ if (event.target.matches(".circle")){ if (event.target.classList.contains("on")){ alert("turn off"); } else { alert("turn on"); } event.target.classList.add("on"); } });

2. Add and remove classes based on the state of the circle

The last step let us differentiate between the "on" state and the "off" state of the circle, but only using alerts. We can use the "add( )" and "remove( )" methods on an element's "classList" to add and remove CSS classes. "remove( )" works just like "add( )". It takes in a single string argument, which represents the class you want to remove.

Replace the alerts with code that adds and removes classes to get the effect in the image above. 
document.addEventListener('click', function(event){ if (event.target.matches(".circle")){ if (event.target.classList.contains("on")){ event.target.classList.remove("on"); } else { event.target.classList.add("on"); } } });