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

What is wrong with my code?

Would anyone be so kind as to tell me what is wrong with my code, thank you

var html = '';


function randomColor () {
var red = Math.floor(Math.random() * 256 );
var green = Math.floor(Math.random() * 256 );
var blue = Math.floor(Math.random() * 256 );
var rgbColor =  'rgb(' + red + ',' + green + ',' + blue + ')';
 return rgbColor;
};

for ( var i = 1; i <= 10; i += 1 ) {
  html += '<div style="background-color:' + rgbColor + '"></div>';
}

document.write(html);

2 Answers

Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

I'd also note that your randomColor function which is generating your random color is returning a string that sets your inline style. But it's not returning it anywhere, because it's never called. Instead, you're trying to access the rgbColor variable inside your for loop. But rgbColor doesn't exist inside that scope. It only exists inside that function. Instead of using rgbColor use a call to the randomColor function. Hope this helps :sparkles:

Thanks could you please write the code here, i can't seem to get it right. Thank you so much

Jennifer Nordell
seal-mask
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

Sure! This is how I reworked your code. Note that I added a greeting to you to give the div at least a default size.

var html = '';

function randomColor () { 
    var red = Math.floor(Math.random() * 256 ); 
    var green = Math.floor(Math.random() * 256 ); 
    var blue = Math.floor(Math.random() * 256 ); 
    var rgbColor = 'rgb(' + red + ',' + green + ',' + blue + ')'; 
    return rgbColor; 
};

for ( var i = 1; i <= 10; i += 1 ) { 
    html += '<div style="background-color: '+ randomColor() + '">Hi, Ivana!</div>'; 
}

document.write(html);

Hope this helps! :sparkles:

Thank you so much :)