Reputation: 68
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
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
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