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![](https://ecs-static.teamtreehouse.com/assets/views/marketing/shared/community-banner-white-47072046c51352fe6a69f5e691ff5700b28bb11d45197d7bdf066d9ea3f72d0c.webp)
![jeffe otto](https://secure.gravatar.com/avatar/a8b314cbb27396b1ea0b12d8eef22bf1?s=96&d=https%3A%2F%2Fecs-static.teamtreehouse.com%2Fassets%2Fcontent%2Fdefault_avatar-445fbbabfc8dc9188fb5967fe43322ee0c3e0dd1e10f378bf8343784af5a13eb.webp&r=pg)
jeffe otto
10,561 PointsWay 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](https://uploads.teamtreehouse.com/production/profile-photos/969492/micro_tool_chess_set_2.jpg)
Steven Parker
230,688 PointsIf 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](https://secure.gravatar.com/avatar/a8b314cbb27396b1ea0b12d8eef22bf1?s=96&d=https%3A%2F%2Fecs-static.teamtreehouse.com%2Fassets%2Fcontent%2Fdefault_avatar-445fbbabfc8dc9188fb5967fe43322ee0c3e0dd1e10f378bf8343784af5a13eb.webp&r=pg)
jeffe otto
10,561 PointsThat'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);