Jump to content

Changing div backgroundColor dynamically


Recommended Posts

Hi!I've got a slight problem I'm just not able to work out.I'm trying to change the backgroundColor of a div to the backgroundColor of another div, by clicking on the second one with the following code, but it doesn't work and I have no idea why. Html:

<div id="chosenColor"></div>  <div id="c1" onClick="changeColor(this.style.backgroundColor)"></div>


function changeColor(color){document.getElementById("chosenColor").style.backgroundColor = color;alert(color.innerHTML);}


#chosenColor {background-color: black;}#c1 {background-color: yellow; }

Thank you in advance!

Link to comment
Share on other sites

Thanks. I guess I forgot to take that out. I used the alert() to see if the function was working at all... I'm just gonna post the whole code because I went through it for hours and still have no clue what could be wrong... (since it is still not working)HTML(+js):

<html>  <head>    <title>Canvas Paint - Example 5</title><link rel="stylesheet" type="text/css" href="style.css">  </head>  <body>  <script>  function changeColor(color)  {   document.getElementById("chosenColor").style.backgroundColor = color;   alert(color.innerHTML);  }  </script>   <div id="chosenColor"></div>  <div id="c1" onClick="changeColor(this.style.backgroundColor)"></div></body></html>


#chosenColor {width: 40px;height: 40px;background-color: black;}#c1 {width: 20px;height: 20px;background-color: yellow;}

Link to comment
Share on other sites

You are expecting it to pick up the background color set by the css styling, but your code looks for styling set up inline only as in

<div id="c1" style="background-color:yellow;" onClick="changeColor(this.style.backgroundColor)"></div>

for non inline styling as you have used you would have to use code similar to

  function getStyle(el, cssprop){ if (el.currentStyle) //IE  return el.currentStyle[cssprop] else if (document.defaultView && document.defaultView.getComputedStyle) //Firefox  return document.defaultView.getComputedStyle(el, "")[cssprop] else //try and get inline style  return el.style[cssprop]}   function changeColor(el)  {  var bcolor= getStyle(el, 'backgroundColor')  //alert(bcolor);   document.getElementById("chosenColor").style.backgroundColor = bcolor;     }


<div id="c1" onClick="changeColor(this)"></div>

  • Like 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Create New...