Here is a square that changes color onclick. It is just a div (#sq) and css related is like so :
#sq{
background-color: red;
width: 100px;
height: 100px;
}
On click, it should change color :
sq.addEventListener('click', function(){
if(sq.style.backgroundColor == 'red'){
sq.style.backgroundColor = 'blue';
}else{
sq.style.backgroundColor = 'red';
}
})
The first click does not do anything. Even though #sq is red it does not become blue. The second click works though.
Can someone explain this ?