Skip to content Skip to sidebar Skip to footer

Why Change The Color Inside The Div Does Not Work?

Div with the id is clicking, the div with class is not clicking. By clicking div I want to change the color. If the color input within the div class is not working, if it is out of

Solution 1:

The click event is firing for both divs, but your handler only shows the alert if the clicked div has an id, which the first one doesn't have.

You are also using old APIs (getElementsByTagName and getElementsByCalssName) that should really not be used anymore and the solution is much simpler that what you've done:

let color = document.querySelector(".backgroundcolor"); // Get reference to color inputlet targetDiv = document.getElementById("divid"); // Get reference to second div// Set up click event handler on the documentdocument.addEventListener("click", function(evt){
  // Check to see if event originated at a divif(evt.target.nodeName === "DIV"){
    alert("You clicked a div!"); // Act accordingly
  }
});

// Set up change event on color input
color.addEventListener("change", function(evt){
  // Set color of target div
  targetDiv.style.backgroundColor = color.value;
});
#divid{
  width: 450px;
  height: 170px;
  margin: 10px;
  padding: 10px;
  background-color: blue;
}



.divclass{
  width: 450px;
  height: 170px;
  margin: 10px;
  padding: 10px;
  background-color: blue;
}
<divclass="divclass"><inputtype="color"class="backgroundcolor"></div><divid="divid"></div>

Solution 2:

functionBackgroundColor(){

  var x = document.getElementById("backgroundcolor1").value;
   
  document.getElementById("clickedDivId").style.backgroundColor = x;
}
#divid{
  width: 450px;
  height: 170px;
  margin: 10px;
  padding: 10px;
  background-color: blue;
}
.divclass{
  width: 450px;
  height: 170px;
  margin: 10px;
  padding: 10px;
  background-color: blue;
}
<divid="clickedDivId"class="divclass"><inputtype="color"id="backgroundcolor1"onclick="BackgroundColor()"></div><divid="divid"></div>
It is better to use ID. I guess this is what you want. By keep changing the color the background will change as well.

Post a Comment for "Why Change The Color Inside The Div Does Not Work?"