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 trialMagnus Benoni
31,059 PointsQuestion about syntax
In the video Perform: Part 2 in the Creating a simple drawing application project, you use this syntax for setting the RGB values for the box next to the sliders.
My question is, why do you use this syntax
$("#newColor").css("background-color", "rgb(" + r + "," + g + "," + b + ")");
instead of just
$("#newColor").css("background-color", "rgb("r","g","b")");
Thanks!
1 Answer
Dino Paškvan
Courses Plus Student 44,108 PointsThe example you provide:
$("#newColor").css("background-color", "rgb("r","g","b")");
would be invalid JavaScript syntax.
The jQuery .css()
method accepts 3 different combinations of parameters when setting CSS properties:
- A property name string and a value for that property (string or number)
- A property name string and a function which returns a value for that property (returns a string or a number)
- An object containing properties to be set (property-value pairs)
Setting only the background color is the first scenario. So the second parameter must be a string. Your example is invalid JavaScript syntax because that's not how string concatenation is done in JavaScript. You need to use the string concatenation operator (+
).
That's why this snippet: "rgb(" + r + "," + g + "," + b + ")"
produces (for values r = 0
, g = 0
, b = 0
) the following string: "rgb(0,0,0)"
.