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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

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

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  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...

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.