NinjaKlown
NinjaKlown

Reputation: 61

Changing cell background color using a loop?

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++;
}

Upvotes: 0

Views: 1951

Answers (1)

user796446
user796446

Reputation:

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.

Upvotes: 2

Related Questions