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

I was practicing refactoring cause I (****) at it and I had this idea.

a loop that makes an rgb increase to form a color chart. I'm sure it needs polish but this is it

<p id="display"></p>
.color {
    display: inline-block;
    width: 20%;
    margin: 3px;
    padding: 10px 0px;
    margin-left: 8%;
    border: 5px inset #666;
    text-align: center;
}
function print(output){
  document.getElementById("display").innerHTML = output;

}

var html = "";
for(var color = 50; color < 300; color += 50){
  html +=
  '<div style="background:rgb('+color+', 0, 0);" class="color">red</div>'
  html +=
  '<div style="background:rgb(0, '+color+', 0);" class="color">green</div>'
  html +=
  '<div style="background:rgb(0, 0, '+color+');" class="color">blue</div>'
  print(html);
}

1 Answer

Steven Parker
Steven Parker
231,269 Points

Very cool. :+1: I had three ideas upon seeing it:

  • show the color value in each box
  • insure that the range reaches the maximum value
  • you only need to print once, after the string is completely built
var html = "";
for (var color = 55; color < 256; color += 50) {
  html += '<div style="background:rgb('+color+', 0, 0);" class="color">red '+color+'</div>'
  html += '<div style="background:rgb(0, '+color+', 0);" class="color">green '+color+'</div>'
  html += '<div style="background:rgb(0, 0, '+color+');" class="color">blue '+color+'</div>'
}
print(html);

Thanks Steve, I tried printing the value out to the page as well. I like it. About placement of print. In this case it SEEMS to work where it is. Why would I want to move it? I appreciate your feedback.