Vacant 0 Report post Posted August 25, 2004 Okay, my problem is this: Im trying to create a table, with 10 cells. Each is 20x20 px, but has a background colour that is pretty much random (color names taken from an array of 10). This would mean that the cells would be coloured differently, and when the page was reloaded the colours would be different. Well, this is what I got, and it almost worked: [/br]<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">[br][/br]<html>[br]<head>[/br] <title>Untitled</title>[br]</head>[br][/br]<body>[br][/br][/br]<table border="0" border="#FFF">[br]<tr>[br][/br]<script language="javascript">[/br]var number = Math.round(Math.random()*9)[br][/br]var random = new Array(9)[br]random[0] = "salmon"[/br]random[1] = "silver"[br]random[2] = "pink"[/br]random[3] = "purple"[br]random[4] = "seagreen"[/br]random[5] = "orange"[br]random[6] = "green"[/br]random[7] = "yellow"[br]random[8] = "red"[/br]random[9] = "blue"[br][/br]var i;[br][/br]for (i = 1; i < 11; i++) [br] { [/br] document.write("<td width='20px' border='#000' bgcolor='" + random[number] + "' height='20px'> </td>"); [br] }[/br]</script>[br][/br]</tr>[br]</table>[/br]</body>[br]</html> The cells appear as they should, the color is different each time the page is loaded. BUT, shock horror, the individual cells arent different colours. They are, eg, all blue, or all yellow on any one page load. I was aiming for different colours in each different cell each time. How should I go about this?(obviously, there might be a COUPLE that may be of the same colour but thats ok)Thanks guys. Any help or comments at all would be greatly appriciated. Share this post Link to post Share on other sites
Spectre 0 Report post Posted August 25, 2004 That's because only one random number is being generated, and that's at the start of the script. You need to generate a new random number for each loop, eg: for (i = 1; i < 11; i++) [br]{ [/br] var number = Math.round(Math.random()*9)[br] document.write("<td width='20px' border='#000' bgcolor='" + random[number] + "' height='20px'> </td>"); [/br]} I think you'll find that works better. Share this post Link to post Share on other sites
Zenchi 0 Report post Posted August 26, 2004 Ermm.. Just trying to be more effecient (because I'm a noob at javascript/programming )Isn't it possible just to generate a random value for a color instead of defining them in an array? (I've actually learned more from this forum then anything) Share this post Link to post Share on other sites
Vacant 0 Report post Posted August 26, 2004 Thats a good point... I could just use math.random to create random 6 figure numbers (hex codes!) Thats genius! And thanks spectre for the code, it works like it should. I see what I should have done now... Thanks a lot guys. This should be very useful (even if at first it seems pointless!) :D Share this post Link to post Share on other sites