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 post
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 post
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 post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Create New...