Follow the Leader Puzzle explainer

Aim of the puzzle:
This puzzle combines the use of JavaScript concepts (event handlers and arrow functions) and D3 concepts (.selectAll() and 'fill' attribute) to modify shapes.

Specifically, you’ll use an event handler with an arrow function to change the color of multiple shapes at once.

Walk through of solution:
In the code that you start off with, there is an event handler attached to circleButton. When you tap on circleButton, an arrow function runs and every 'circle' changes color. In this puzzle, you’ll add another event handler that does the same thing but with every rectangle, 'rect', and on squareButton.

To complete the puzzle, add sqaureButton.on('click', ___) below the circleButton event handler. Add an arrow function as the second argument of the .on(___, ___) call. Inside the arrow function, select every square using d3.selectAll('rect') and set their 'fill' to pickRandom(color). Now, when you tap on squareButton all the squares will change color.

Sample code solution:

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

squareButton.on('click',()=>{
    d3.selectAll('rect').attr('fill', pickRandom(color))
});

Javascript Concepts: Variable, Event Handler, Arrow Function
D3 Concepts: Attribute, d3.selectAll()
Grasshopper Concepts: pickRandom()
Additional Code (hidden code that runs before the puzzle’s code):

let WIW = window.innerWidth;
let WIH = window.innerHeight;
let color = [...Array(36)].map((_,i)=>`hsl(${10*i},100%,50%)`);

let svg = setupD3();

for (let i = 0; i < 100; i++) {
    svg.append('circle').attr('r',10).attr('cx',20*pickRandom(WIW/20)).attr('cy',20*pickRandom(WIH/20)).attr('fill','blue');
    svg.append('rect').attr('width',20).attr('height',20).attr('x',20*pickRandom(WIW/20)).attr('y',20*pickRandom(WIH/20)).attr('fill','red');
}

let circleButton = svg.append('circle').attr('r',30).attr('cx',35).attr('cy',35).attr('fill','blue').attr('stroke','white').attr('stroke-width',3);
let squareButton = svg.append('rect').attr('width',60).attr('height',60).attr('x',70).attr('y',5).attr('fill','red').attr('stroke','white').attr('stroke-width',3);
1 Like

When you code JavaScript outside of grasshopper and use the arrow function, does the pair of parentheses preceding it have a space between like ( )=>{ or not, like ()=>{

1 Like