Great Pumpkin explainer

The aim of this puzzle: Add an event handler to the pumpkin to make it grow each time you tap it

Walkthrough of the solution: The pumpkin is created at the bottom of the starter code. It’s just an orange circle. The grow() function increases the value of the size variable by 5 and then uses that variable to update the pumpkin's radius using the 'r' attribute. To make the grow() function run each time you tap on the pumpkin, you need to apply an .on('click',...) call to the pumpkin.

At the very bottom of your code, add pumpkin.on(...). That’s the setup to add an event handler to the pumpkin. The 1st argument of the .on(...,...) call is the action that will trigger the event handler. You want that to be a 'click'. The 2nd argument is a callback function that will run when the event trigger (a click or tap) occurs. You want the grow function to run on each click.

To make sure you have the correct order, you can read the command backwards: grow when you 'click' .on() the pumpkin.

Sample code solution:
(Tap below to reveal)

function grow() {
  size += 5;
  pumpkin.attr('r', size);
let size = 20;
let pumpkin = svg.append('circle')
                   .attr('r', size)
                   .attr('cx', 150)
                   .attr('cy', 100)
                   .attr('fill', 'orange');
pumpkin.on('click', grow);

JavaScript Concepts: Assignment Operator (+=), Code Block (function)

D3 Concepts: .append(), .attr('cx',), .attr('cy',), .attr('fill',), .attr(r,), .on('click',)

Hi guys, will this code work?

That works too! The puzzle’s completion logic won’t accept it though, as it doesn’t want the grow() function to be edited in the starter code.


1 Like