Theodore Steiner Theodore Steiner - 2 months ago 8
CSS Question

Changing bg color of div vs. Text

When I attempt to dynamically change the color of text via on click I seem to have no problem using style.color="___" however, this doesn't seem to want to work for the background color of divs. Is there a particular reason for this?



var text = document.getElementById("text");

var square = document.getElementById("square");

text.onclick = function() {
if (this.style.color === "blue") {
this.style.color = "black";
console.log("it worked");
} else {
this.style.color = "blue";
}
};

square.onclick = function() {
if (this.style.backgroundColor === "#ccc") {
this.style.backgroundColor = "#fff";
} else {
this.style.backgroundColor = "#ccc";
}
};

#text {
color: blue;
}
#square {
height: 50px;
width: 50px;
background-color: #ccc;
transition: all .5s ease;
}

<p id="text">Test</p>

<div id="square"></div>




Answer

A few issues with your code:

  1. When checking an element's style definition, you are looking for inline styles, not styles stored in CSS. That's why the link text doesn't change from blue to black on the first click, it's actually falling into the else condition first and then setting an inline style to blue. After the first click, an inline style has been set and the clicking works correctly.
  2. You are checking for #ccc but the browser is converting this to an inline style of rgb(204, 204, 204) - so you are actually checking if #ccc is equal to rgb(204, 204, 204), which they are not, thus your color never changes.

To check an element's styles including styles defined in stylesheets, you can use getComputedStyle():

window.getComputedStyle(square,null).getPropertyValue("background-color");

You're probably better off using classes for the different colors rather than checking inline styles. You can create semantic names for your classes and switch to different colors as needed without needing to check specific CSS values in JavaScript.

var text = document.getElementById("text");
var square = document.getElementById("square");

text.onclick = function() {
  if (this.className === "text-blue") {
    this.className = 'text-black';
  } else {
    this.className = "text-blue";
  }
};

square.onclick = function() {
  if (this.className === "square-grey") {
    this.className = "square-white";
  } else {
    this.className = "square-grey";
  }
};
#text.text-blue {
  color: blue;
}

#text.text-black {
  color: black;
}

#square {
  height: 50px;
  width: 50px;
  transition: all .5s ease;
}

#square.square-grey {
  background-color: #ccc;
}

#square.square-white {
  background-color: #fff;
}
<p id="text" class="text-blue">Test</p>

<div id="square" class="square-grey"></div>