Color Clicker explainer

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: There is code that runs before the puzzle’s code that sets the size and location of the SVG shape, and defines the variable color.

seperti ini kah? Hehehe :smile: :wink:

1 Like

@Tri_Putra_Alexander Kerja bagus :slight_smile:

(Used google translate hopefully that says good job :slight_smile: )

1 Like

Hi guys, I’ve completed the puzzle, but just out of curiosity can someone please explain why the following code doesn’t also work?

Hey there,

The 2nd argument of .on() needs to be a function to run when the circle is clicked.

Wrapping lines of code in a function means they are stored in the computer’s memory, and retrieved when they are called (in this case, when then circle is clicked).

The .on() function will throw an error here as the line of code is not a function.

You could try declaring the function separately, and then putting the function’s identifier (its name, without parentheses after it) as the 2nd argument of .on(), like this:

function changeColor() {
    circle.attr('fill', pickRandom(color));
}

circle.on('click', changeColor);

Or, you could declare the function anonymously (a function without a name) inside .on(), like this:

circle.on('click', function() {
    circle.attr('fill', pickRandom(color));
});

Or finally, you could write it as an anonymous arrow function, like this:

circle.on('click', () => {
    circle.attr('fill', pickRandom(color));
});

Hope this helps!
Ben

1 Like

Got it. Thanks, Ben!