javasript random colors for div background


#1

I am trying to create hex colors randomly that will change the background of a div. It should repeat until a code tells it to stop. I have the code to generate the color I think.

      function getRandomColor() {
      var letters = '0123456789ABCDEF';
      var hash = '#';
       for (var i = 0; i < 6; i++) {
       hash += letters[Math.floor(Math.random() * 16)];
       }
       document.write(hash);
      return hash;
    }

I also need to display the hex code created, I know I need to probably write functions that call functions and some time event to slow down the color display. I haven’t really got the function down yet.
This is my html

       <html>
	<head>
		</head>
	<body>
		<div  id="bgcolor"  style="width: 700px; margin: auto; margin-top: 100px; border: 1px solid black; padding: 
               5px; background-color: #E7E7E7;">
			<p id="text">Power is of two kinds. One is obtained by the fear of punishment and the other by acts 
                          of love. Power based on love is a thousand times more effective and permanent then the one 
                         derived from fear of punishment.<br/><b>Mahatma Gandhi</b><br/>
			<br /><hr />
			Change Background Color&nbsp;&nbsp;&nbsp; Color Hex Value:<span id="color"></span><br />
			Stop Changing Background Color<br />			
		</div>
	  </body>
    </html>

Ialso have to write code see less and see more on the text but I haven’t started on that yet.
Thanks


#2

Your random color function looks fine, except for the document.write(). You’ll want to get rid of that. In fact, you should avoid using document.write whenever possible. Depending on what you’re after, there are other, better ways to do what you may be trying with document.write.

For the color randomization it sounds like you want to use setInterval. In fact that link has an example for alternating colors which is very similar to what you’re after, but it sounds like you’re version of changeColor would want to be in a button rather then the onload used there?


#3

Thanks senocular! You are always so helpful!