Traffic Lights explainer

Traffic Lights

The aim of this puzzle: Turn the bottom traffic light green.
Walkthrough of the solution: When you run the starter code, you see that the bottom circle is purple instead of green. If you check the code, it seems like the problem is in the last command: bottomCircle.attr('fill', 'purple'); So, what is actually going on? bottomCircle is an identifier, or variable, that represents the bottom circle as you would expect. .attr() is used to choose an attribute or property of the whichever identifier it’s attached to and change the value of that attribute. In this line, the .attr() is finding the 'fill' attribute which is the color that the shape is filled in with. You can see it’s being filled with 'purple' when it should be 'green'. All you have to do is change the value of that one string.
Sample code solution:
(Tap below to reveal)

topCircle.attr('fill', 'red');
middleCircle.attr('fill', 'orange');
bottomCircle.attr('fill', 'green');

JavaScript Concepts: Identifiers, Member Expression
D3 Concepts: .attr(‘fill’,)

Additional Code (hidden code that runs before the puzzle’s code):

var topCircle = svg.append('circle').attr('r', 25).attr('cx', 25).attr('cy', 25);
var middleCircle = svg.append('circle').attr('r', 25).attr('cx', 25).attr('cy',75);
var bottomCircle = svg.append('circle').attr('r', 25).attr('cx', 25).attr('cy',125);

Why is the color placed as a string? I thought that a string was just words to be printed out but, in this case, it fills with the color itself, not the word “green”. Is this related to the function .attr()? What am I missing?

Yeah, JS knows that the color red must be used when you use .attr('fill', 'red'). You are telling to fill the shape with red, the color red.

Like drawBox() and drawBoxes() use string to print colored squares.

2 Likes

how to use and run this code in real life, and are the above codes changed now ?
please tell me how to run the above code.