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 trialShung Chen
6,526 PointsHow to incorporate function into function
I was trying to randomise the numbers but the function fails
var html = '';
function randomRGB(){
return Math.floor(Math.random() * 256);
}
function randomRGBcolor(){
return `rgb(randomRGB(), randomRGB(), randomRGB()` //want them to become rgb (xxx,xxx,xxx)
}
for (numOfColor = 1; numOfColor <= 5; numOfColor ++) {
html += '<div style="background-color:' + 'randomRGBcolor()' + '></div>'; // want to incorporate the function randomRGBcolor()
}
document.write(html);
3 Answers
ygh5254e69hy5h545uj56592yh5j94595682hy95
7,934 Points// I'll just list all the changed that I made to your code
// Your code
return `rgb(randomRGB(), randomRGB(), randomRGB()`
// Changed code
return `rgb(${randomRGB()}, ${randomRGB()}, ${randomRGB()})`
// Your code (nothing wrong with your code here, its just a personal preference to use for loop like this (Changed code))
for (numOfColor = 1; numOfColor <= 5; numOfColor ++)
// Changed code
for (numOfColor = 0; numOfColor < 5; numOfColor ++)
// Your code
'<div style="background-color:' + 'randomRGBcolor()' + '></div>';
// Changed code
`<div style="background-color:${randomRGBcolor()}"><h1>hello</h1></div>`;
Shung Chen
6,526 PointsThank you. You made my day - didn't sleep last night to learn this and it's 10:30am in Australia now
ygh5254e69hy5h545uj56592yh5j94595682hy95
7,934 PointsMy pleasure. Go rest soon :D
ygh5254e69hy5h545uj56592yh5j94595682hy95
7,934 PointsThere you go. I added a <h1> tag so that I can see the text better, but anyways, this should work just like you wanted it Look over the code and see how I was able to achieve that. Compare it to yours and see where you made a few mistakes.
var html = '';
function randomRGB(){
return Math.floor(Math.random() * 256);
}
function randomRGBcolor(){
return `rgb(${randomRGB()}, ${randomRGB()}, ${randomRGB()})` //want them to become rgb (xxx,xxx,xxx)
}
for (numOfColor = 0; numOfColor < 5; numOfColor ++) {
html += `<div style="background-color:${randomRGBcolor()}"><h1>hello</h1></div>`; // want to incorporate the function randomRGBcolor()
}
document.write(html);
Shung Chen
6,526 Pointscan i ask apart from the template literals where the function name randomRGB are surrounded by ${} got to re-visit content about template literals
is there other changes?