0

In a loop, I need to generate a random number and convert it to a random color. Then, using the generated color, change the background color of the cell. Iterate 10 times and change the colors from the leftmost cell to the rightmost cell. Problem is im not sure how to do this. The following is my code to generate the table i need. I'm not sure this could work because how can i access an individual cell without using id?

<table>
<tr>
<script type="text/javascript">
var rownum = 1; var colnum = 1;
while (rownum <= 1){
document.write("<tr>");
while (colnum <= 10) {
document.write("<td>"+colnum+"</td>");
colnum++;
}
document.write("</tr>");
colnum = 1; rownum++;
}
NinjaKlown
  • 61
  • 2
  • 2
  • 8
  • Explain a little bit more. Should all the cells have a different colour? Or the cells of a column be the same colour? Or the cells of a row be the same colour? – Matheus208 Oct 30 '15 at 15:47
  • Look at CSS n-th selectors and changing css color rgba values (They range from 0-255) and use Java-scripts Random generator to generate these numbers. – Dean Meehan Oct 30 '15 at 15:48
  • 1
    Do you need to use Javascript only, are you allowed to use jQuery? – AGE Oct 30 '15 at 15:48
  • Don't use `document.write`, create the elements in memory and append them at the end. – Bartek Banachewicz Oct 30 '15 at 15:52
  • Could you post a jsfiddle of what you have tried so far? –  Oct 30 '15 at 15:55
  • @AGE I have to use JavaScript for the table, how I loop the colors it doesn't matter.@Matheus208 unfortunately that's all the information I have I'm assuming that each column cell is its own color. – NinjaKlown Oct 30 '15 at 16:00

1 Answers1

2

Here is a working example for you.

JSFiddle example

var myColors = [];
for (var ii=0;ii<10;ii++){
myColors.push({value:getRandomColor()});
}

var myHtml = '<table><tr>';

for (var xx=0;xx<10;xx++){

var temp ='<td style="background-color:'+myColors[xx].value+'">Cell     '+xx+'</td>'

myHtml+=temp;
}

myHtml +='</tr><table>'

console.log(myHtml);

var myElement = document.getElementById('content');

myElement.innerHTML = myHtml;



//http://stackoverflow.com/questions/1484506/random-color-generator-in-javascript
function getRandomColor() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++ ) {
    color += letters[Math.floor(Math.random() * 16)];
}
return color;
}

NOTE: I would say doing in-line style is a bad thing. But...in this case it is the shortest solution.

  • Wow thank you so much for doing that. I'm pretty sure that's what I need, if I want it to change the colors of the cell one at a time to make a kind of strobe effect would I have to change the code? Or could I just use jquery? – NinjaKlown Oct 30 '15 at 17:00
  • The answer to your question is yes. :) To change color you could do something with a timeout function and then change td background color. Could also do something similar with jQuery. –  Nov 02 '15 at 17:16