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 trialalfonso ruiz
Front End Web Development Techdegree Student 8,851 PointsWhy does it print circles in greyscale instead of color?
Assuming I wanted to refactor everything into one function that generates an rgb value like in the code below. Why does this print the circles only on a greyscale instead of color?
var html = '';
function rgbGenerator() {
var randomRgbNumber = Math.floor(Math.random() * 256 );
var color = 'rgb(';
color += randomRgbNumber + ',';
color += randomRgbNumber + ',';
color += randomRgbNumber + ')';
return color;
}
function print(message) {
document.write(message);
}
for (var i = 1; i <= 10; i++) {
html += '<div style="background-color:' + rgbGenerator() + '"></div>';
}
print(html);
1 Answer
Konrad Traczyk
22,287 PointsYou're randomizing only once, so you put the same number as red, green and blue and that's why its greyscale. To make this work well you need 3 numbers to be randomized instead of one.
Like this:
function rgbGenerator() {
var randomRgbNumberRed = Math.floor(Math.random() * 256 );
var randomRgbNumberGreen = Math.floor(Math.random() * 256 );
var randomRgbNumberBlue = Math.floor(Math.random() * 256 );
var color = 'rgb(';
color += randomRgbNumberRed + ',';
color += randomRgbNumberGreen + ',';
color += randomRgbNumberBlue + ')';
return color;
}
alfonso ruiz
Front End Web Development Techdegree Student 8,851 Pointsalfonso ruiz
Front End Web Development Techdegree Student 8,851 PointsAhhh, of course. Thanks Konrad!