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

Tammi Carter
Tammi Carter
5,360 Points

Instead a multi-color Loops, my code is showing 10 dots of the same color at each loop. Can anyone tell me why ?

var html = ''; var red; var green; var blue; var rgbColor;

function rgbColor() { return Math.floor(Math.Random() * 256 ); }

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>';

for (var i = 1; i < 10; i++) { rgbColor = 'rgb(' + red + ',' + green + ',' + blue + ')'; html += '<div style="background-color:' + rgbColor + '"></div>'; } document.write(html);

3 Answers

To get random colors you will have to set red, green and blue within the loop.

var html = '';
var red;
var green;
var blue;
var rgbColor;

for (var i = 1; 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);

Otherwise you are just repeating the values set before the loop.

Steven Parker
Steven Parker
231,275 Points

This code selects random values to create a color, and then the loop creates 10 elements using that (same) color.

To make each element a different color, you can move the lines that assign red, blue, and green inside the loop so they get picked fresh for each one.

Tammi Carter
Tammi Carter
5,360 Points

I understand now! Thank you so much Steven and Kris❗️ ✌🏾 I appreciate you both.