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 trialJade Newbury
Courses Plus Student 10,564 PointsMy solution with a for loop
Here is my solution:
var red;
var green;
var blue;
var rgbColor;
var html = '';
for (var i =0; i <10; i++) {
red = Math.floor(Math.random() * 256 );
green = Math.floor(Math.random() * 256 );
blue = Math.floor(Math.random() * 256 );
rgbColor = 'rgb(' + red + ',' + green + ',' + blue + ')';
html += '<div style="background-color:' + rgbColor +'"></div>';
}
document.write(html);
2 Answers
Jacob Mishkin
23,118 PointsThat's great! But I'm not a huge fan of writing the math.random equation over and over. How about putting that in a function and returning the value of the equation, then plugging that in as the values for red, green, and blue.
Philip Campbell
15,324 PointsSomething like this?
var html = '';
var red;
var green;
var blue;
var rgbColor;
function randomRGB() {
return Math.floor(Math.random() * 256 );
}
for ( var i = 0; i <= 10; i += 1 ) {
red = randomRGB();
green = randomRGB();
blue = randomRGB();
rgbColor = 'rgb(' + red + ',' + green + ',' + blue + ')';
html += '<div style="background-color:' + rgbColor + '"></div>';
}
document.write(html);
Philip Campbell
15,324 PointsApparently, I'm terrible at code blocks.
Jacob Mishkin
23,118 PointsYup, but you are printing 11 divs not 10.