0

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 ?

1 Answers1

0

From MDN ElementCSSInlineStyle.style:

The style property is used to get as well as set the inline style of an element. When getting, it returns a CSSStyleDeclaration object that contains a list of all styles properties for that element with values assigned for the attributes that are defined in the element's inline style attribute.

When you are clicking it for the first time sq.style.backgroundColor is returning a blank value and the flow is moving to the else block. Here you are setting inline style of the square that is why second click is working.

You can use window.getComputedStyle() method that returns an object containing the values of all CSS properties of an element. MDN Documentation

Andrew Li
  • 55,805
  • 14
  • 125
  • 143