Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialRahul Raj
717 Pointswhy these codes are not working??
<script> var html=' '; var red; var green; var blue; var rgbColor; for (var i=1; i<10; i +=1) { red=blue=green= Math.floor(Math.random()*256);
rgbColor='rgb('+red+','+green+','+blue+')'; html += '<div style="background-color:'+rgbColor+'"></div>'; } document.write(html); </script> //where is the fault?
1 Answer
matt mccherry
4,493 PointsEach time your script is passing through the loop it's setting all of the rgb colors to the same value.
//This is your problem, they are all equal the same random value.
//We need the value to be different for each one!
red=blue=green= Math.floor(Math.random()*256)
Here's a simple solution!
var html='';
var red;
var green;
var blue;
var rgbColor;
for (var i=1; i<10; i +=1) {
red = Math.floor(Math.random()*256);
blue = Math.floor(Math.random()*256);
green = Math.floor(Math.random()*256);
rgbColor = 'rgb(' + red + ',' + green + ',' + blue + ')';
html += '<div style="background-color:' + rgbColor + '"></div>"';
}
document.write(html);
// Alternatively accomplish with a function like so...
function getRandomColors() {
red = Math.floor(Math.random()*256);
green = Math.floor(Math.random()*256);
blue = Math.floor(Math.random()*256);
//set all the global var colors to a random value between 0-256
}
for (var i=1; i<10; i +=1) {
getRandomColors();
rgbColor = 'rgb(' + red + ',' + green + ',' + blue + ')';
html += '<div style="background-color:' + rgbColor + '"></div>';
}
document.write(html);
Greg Witt
27,133 PointsGreg Witt
27,133 PointsI had experienced the same problem thanks for taking the time to answer that question. Great code