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 trial

JavaScript JavaScript Loops, Arrays and Objects Simplify Repetitive Tasks with Loops The Refactor Challenge

Jake Guss
seal-mask
.a{fill-rule:evenodd;}techdegree
Jake Guss
Front End Web Development Techdegree Student 5,855 Points

My solution has a problem.

//For some reason, all the colors in each div are the same. Shouldn't they be randomized? Or does calling the function more than once produce the same result?

var html = '<div style="background:'+ranColor()+'"></div>';

function ranColor () {
var red = Math.floor(Math.random() * 256 );
var green = Math.floor(Math.random() * 256 );
var blue = Math.floor(Math.random() * 256 );
var rgbColor = 'rgb(' + red + ',' + green + ',' + blue + ')';
return rgbColor;
}

for (var i = 0; i < 10; i += 1) {
  document.write(html);
}

1 Answer

David Bath
David Bath
25,940 Points

The problem is that when the html variable gets defined, the ranColor() function is called and creates a single random color. That random color becomes part of a static string. Then when you go through the loop to write the divs to the page they are all using that same string.

What you'll need to do is call the ranColor() function inside the loop. That way each div will get a different random color. Here's one way to format it:

for (var i = 0; i < 10; i += 1) {
  var html = '<div style="background:'+ranColor()+'"></div>';
  document.write(html);
}