Jump to content

Why doesn't this work?


tjmbc

Recommended Posts

I am trying to write a simple function that makes a div change background colors randomly. Here's the code so far:

 

	function setBackground()
	{
          var digit = new array('0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'); //Creates an array with hex digits.
          digit.sort(function() {return 0.5 - Math.random()}); //Randomizes the above array.
          clr = "+" + digit[0] + digit[1] + digit[2] + digit[3] + digit[4] + digit[5]; //Puts the array in color form (ie. #00ff00).
          boxdiv.style.backgroundColor = clr; //Sets the background color of the div tag.
	}

 

The code doesn't work. If I put the line...

 boxdiv.style.backgroundColor = "#00ff00"; 

... it will change the color. (The function is tied to a buttons 'onClick' event). Anyone know what I'm missing?

Link to comment
https://forums.phpfreaks.com/topic/137579-why-doesnt-this-work/
Share on other sites

Array needs to be capitalized, and you can't just call boxdiv. If it's on the onclick for the element, just pass itself to the function, like so:

<script type="text/javascript">
      function setBackground(ele)
      {
          var digit = new Array('0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'); //Creates an array with hex digits.
          digit.sort(function() {return 0.5 - Math.random()}); //Randomizes the above array.
          clr = "#" + digit[0] + digit[1] + digit[2] + digit[3] + digit[4] + digit[5]; //Puts the array in color form (ie. #00ff00).
          ele.style.backgroundColor = clr; //Sets the background color of the div tag.
      }
</script>
<div style="width:100px;height:100px;" onclick="setBackground(this)"></div>

Link to comment
https://forums.phpfreaks.com/topic/137579-why-doesnt-this-work/#findComment-719071
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.