The aim of this puzzle: Connect the buttons to their functions.
Walkthrough of the solution: The functions are all ready to go, but they’re never being called in the program. You want to use .on('click',...)
to connect the button variable to the function. A trick to remember what each part of the .on('click',...)
call does is to read it backwards – if you want the drop function to run every time you click on the red button, then you use redButton.on('click', drop);
It’s the same way for the blue button except that one should run the cleanUp
function.
Sample code solution:
(Tap below to reveal)
function drop() {
svg.append('circle')
.attr('r', 15)
.attr('fill', pickRandom(color))
.attr('cx', pickRandom(slot))
.attr('cy', 0)
.transition()
.duration(2000)
.ease(d3.easeBounceOut)
.attr('cy', 165);
}
function cleanUp() {
d3.selectAll('circle')
.transition()
.duration(1000)
.attr('cx', 500)
.ease(d3.easeCubicIn)
.remove();
}
redButton.on('click', drop);
blueButton.on('click', cleanUp);
JavaScript Concepts: Code Block (function, if statement), Call Nesting, Member Expression, Identifiers, Calling Functions, Identifiers
Grasshopper Concepts: pickRandom()
D3 Concepts: .append(), .attr(‘r’,), .attr(‘fill’,), .attr(‘cx’,), .attr(‘cy’,), .transition(), .duration(), .ease(), .selectAll(), .remove(), .on(‘click’,)
Additional Code (hidden code that runs before the puzzle’s code):
let color = [...Array(36)].map((_,i)=>`hsl(${10*i},100%,50%)`);
//Tube
svg.append('path').attr('d','M0 0 L0 32 C0 44 4 48 16 48 L30 50 L30 30 C12 32 16 36 16 0 Z').attr('fill','silver').attr('transform','scale(2) translate(4 40)').attr('stroke','darkgrey');
//redButton
// Backplate
svg.append('rect').attr('x',0).attr('y',0).attr('width',50).attr('height',50).attr('fill','grey').attr('stroke','darkgrey');
// Button depth
var redButton = svg.append('rect').attr('x',5).attr('y',6).attr('width',40).attr('height',40).attr('fill','darkred');
// Button
var redButton = svg.append('rect').attr('x',5).attr('y',3).attr('width',40).attr('height',40).attr('fill','red');
//blueButton
// Backplate
svg.append('rect').attr('x',0).attr('y',60).attr('width',50).attr('height',50).attr('fill','grey').attr('stroke','darkgrey');
// Button depth
var blueButton = svg.append('rect').attr('x',5).attr('y',66).attr('width',40).attr('height',40).attr('fill','blue');
// Button
var blueButton = svg.append('rect').attr('x',5).attr('y',63).attr('width',40).attr('height',40).attr('fill','dodgerblue');
//Slots
var numDiv = 7;
var slotWidth = 30;
for (var i=0; i<numDiv; i++) {
svg.append('rect').attr('x',65+i*(slotWidth+5)).attr('width',5).attr('height',30).attr('fill','silver');
}
var slot = [];
for (var i=0; i<numDiv-1; i++) {
slot[i] = 65+5+(i*(slotWidth+5))+15;
}