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, Part 2

Refactoring challenge code much better

Hi everybody,

I just Improved the challenge code with a function to create RGB colors with parameters, like this:

function rgbColors(red, green, blue)

I also added RGBA witch is very cool.

This is open source and available at : https://github.com/masihtak/RandomCssColors

Hope you enjoy (:

Ioannis Leontiadis
Ioannis Leontiadis
9,828 Points

Nice work! I have opened an issue for refactoring the rgbaColors() just in case! This will also help you getting familiar with githubs' issues functionality if you are not already : )

Seth Roope
Seth Roope
6,471 Points

That's nice masihabjadi, I was going a similar direction with my code.

You could take it even further and nest your functions so it is just one function generating the random colors like so...

var html = '';

function rgbaColor() {
  function randomRGB() {
    return Math.floor(Math.random() * 256 );
  }
  function alpha() {
    return Math.random().toFixed(1);
  }
  if (alpha == 0.0) alpha = 0.1;

  return 'rgba(' + randomRGB() + ',' + randomRGB() + ',' + randomRGB() + ',' + alpha() + ')';  
}

for (var i = 0; i < 160; i++) {
  html += '<div style="background-color:' + rgbaColor() + '"></div>';
}

document.write(html);