Super Hero Gang SHG
Super Hero Gang SHG

Reputation: 68

Learing of if and else

I have these two uls, when you click on them they change color to red, but when you click on them again they should change to the color blue. What am I doing wrong with the If and Else statement?

It seems logical to me that if it is true, then switch to red otherwise be blue. Can you help me understand?

const ul = document.createElement('ul');
document.body.appendChild(ul);

const li1 = document.createElement('li');
const li2 = document.createElement('li');
ul.appendChild(li1);
ul.appendChild(li2);

function colors(evt) {
  if(true) {
  evt.target.style.color = 'red';
  } else {
  evt.target.style.color = "blue";
  };
};
ul.addEventListener('click', colors, false);

Upvotes: 1

Views: 63

Answers (2)

Boris Sokolov
Boris Sokolov

Reputation: 1793

if(true) is not the criteria you shall use here

const ul = document.createElement('ul');
document.body.appendChild(ul);

const li1 = document.createElement('li');
const li2 = document.createElement('li');
ul.appendChild(li1);
ul.appendChild(li2);

function colors(evt) {
  if(evt.target.style.color === 'blue') {
  evt.target.style.color = 'red';
  } else {
  evt.target.style.color = "blue";
  };
};
ul.addEventListener('click', colors, false);

Upvotes: 1

Dmytro Huz
Dmytro Huz

Reputation: 1554

here is fixed function:

function colors(evt) {
  if(evt.target.style.color == 'blue') { //this condition allows you to check the current color and change it to the opposite one. 
  evt.target.style.color = 'red';
  } else {
  evt.target.style.color = "blue";
  };
};

Upvotes: 1

Related Questions