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

1

I'm having a problem with my Javascript code, I can not change the background of a div, so 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 the div it changes color, clicked again it becomes white again.

I look forward to your help.

    
asked by anonymous 26.09.2017 / 07:32

1 answer

0

Three problems:

  • When you define style in CSS, the .style attribute is empty because it is applied to the DOM element. You have to use window.getComputedStyle .

  • When you define style in CSS the browser gives you numerical RGBs (I'm not sure if all browsers behave this way)

  • The syntax in style.backgroundColor=="FFFFFF" is wrong, it should 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>
    
26.09.2017 / 07:38