The aim of this puzzle: Make the circle change to a random color each time you tap it.
Walkthrough of the solution: When you run your program, it sees that you created a function called changeColor()
. It doesn’t run it right away, but waits until another part of your code calls it into action. So the first thing to actually run is the circle.attr('fill', pickRandom(color));
at the very beginning. This sets the circle
to a random color. Next, the function is skipped over, and it moves on to the circle.on('click', changeColor);
line. This part is tricky, but it helps if you read it backwards: it will run the function changeColor
once you 'click'
.on()
the circle. So, you click on the circle, and it turns black because you need to look inside the function where you set the 'fill'
attribute and change it to pickRandom(color)
just like the first line does. Your function should run the same code as the first line, but it needs to run every time you tap the circle, and that is exactly what the last line of the program does.
Sample code solution:
(Tap below to reveal)
circle.attr('fill', pickRandom(color));
function changeColor() {
circle.attr('fill', pickRandom(color));
}
circle.on('click', changeColor);
JavaScript Concepts: Code Block (function), Calling Functions, Call Nesting, Identifiers
Grasshopper Concepts: pickRandom()
D3 Concepts: .attr(‘fill’,), .on(‘click’,)
Additional Code (hidden code that runs before the puzzle’s code):
var circle = svg.append('circle').attr('r',window.innerHeight/2-20).attr('cx',window.innerWidth/2).attr('cy',window.innerHeight/2);
let color = [...Array(36)].map((_,i)=>`hsl(${10*i},100%,50%)`);