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

jeffe otto
jeffe otto
10,561 Points

Way around this function

I´ve been trying to put it all together, but i had to write the math random 3 times, otherwise it ends up with repeated numbers like 111,111,111 or 15,15,15 which causes black, white and grays divs. Any suggestion?

Thanks

var html = ´´;
var rgbColor;


function makeColors(){
    var color1 =  Math.floor(Math.random() * 256 ) ;
  var color2 =  Math.floor(Math.random() * 256 ) ;
  var color3 =  Math.floor(Math.random() * 256 ) ;

  var color = 'rgb(';
   color += color1  + ',';
   color += color2  + ',';
   color += color3  + ')';
   return color;
}



function print(message){
  document.write(message);
}

for (var i = 0; i < 10; i++) {

    rgbColor = makeColors();
    html += '<div style="background-color:' + rgbColor + '"></div>';
}
print(html);

2 Answers

Steven Parker
Steven Parker
230,274 Points

If you want 3 different colors, you must use 3 random values, but you can consolidate the process by creating a function that generates a random color value, and then calling it 3 times to get the actual color:

const rc = _=> Math.floor(Math.random() * 256);
const makeColors = _=> `rgb(${rc()},${rc()},${rc()})`;
jeffe otto
jeffe otto
10,561 Points

That's it, the generating random number must be a function. Thank you very much!! This is how it worked for me:

var html = '';
var rgbColor;


function makeColors(){

let rc = () => {return Math.floor(Math.random() * 256 )};

 let  color = `rgb(${rc()},${rc()},${rc()})`;

   return color;

};



function print(message){
  document.write(message);
}

for (var i = 0; i < 1000; i++) {

    rgbColor = makeColors();
    html += '<div style="background-color:' + rgbColor + '"></div>';
}
print(html);