How to change the Color background of a DIV with Class and Id?

Asked

Viewed 802 times

1

I’m having a problem with my Javascript code, I can’t change the background of a div, and I set it in CSS with a class and its color is white.

function escolha(id){
	if(document.getElementById(id).style.backgroundColor=="#FFFFFF"){
		document.getElementById(id).style.backgroundColor="#ccf2ff";
	}
	else{
		document.getElementById(id).style.backgroundColor=="FFFFFF"
	}
}
.bc{
	float:left;
	width:150px;
	height:200px;
	box-shadow: 5px 5px 5px #888888;
	background-color:#FFFFFF;
	margin-left:10px;
	margin-top:10px;
}
	<div class="bc" id="b1" onclick="escolha(this.id)">
			<img src="images/af.jpg" height="150" width="100"> 
			<p>ABUBUBUB</p>					
		</div>	

The command is simple: Clicked on the div it changes color, clicked again it turns white.

I sincerely hope for help.

1 answer

0


Three problems:

  • when you set the style in CSS the attribute .style is empty because it is applied to the DOM element. You must use window.getComputedStyle.

  • when you define the style in CSS the browser gives you numeric Rgbs (I’m not sure if all browsers behave that way)

  • the syntax in style.backgroundColor=="FFFFFF" is wrong, must be == and # in the color code

Suggestion:

function rgb2hex(rgb) {
  // de https://stackoverflow.com/a/3627747/2256325
  rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);

  function hex(x) {
    return ("0" + parseInt(x).toString(16)).slice(-2);
  }
  return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}

function escolha(el) {
  var style = el.style.backgroundColor;
  style = style && rgb2hex(el.style.backgroundColor);
  if (!style || style == '#ffffff') {
    el.style.backgroundColor = "#ccf2ff";
  } else {
    el.style.backgroundColor = "#ffffff"
  }
}
.bc {
  float: left;
  width: 150px;
  height: 200px;
  box-shadow: 5px 5px 5px #888888;
  background-color: #FFFFFF;
  margin-left: 10px;
  margin-top: 10px;
}
<div class="bc" id="b1" onclick="escolha(this)">
  <img src="images/af.jpg" height="150" width="100">
  <p>ABUBUBUB</p>
</div>

  • My God, I had a third bug, I put a == instead of =, it worked dude, I had not even noticed, must be sleep, thanks for the help.

  • @Ruyneto I edited, also missing one # and I came up with another idea.

  • 1

    I understood your addition, return the cute code, thanks man, seriously, at this time help me.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.