Color Field Puzzle Explainer


Aim of the puzzle:
This puzzle uses previously taught JavaScript concepts (variables and event handlers) with previously taught D3 concepts (transition method, duration method, and fill attribute).

Specifically, you’ll use an event handler and a variable to animate the changing 'fill' attribute of an SVG shape.

Walk through of solution:
In the code that you start off with, there are two functions, changeBottom and changeTop, and two event handlers. The changeBottom function creates a variable, randomColor, and sets an incomplete .transition() animation on bottom. The animation isn’t complete because it’s missing an attribute and value for bottom to transition to. The changeTop function does the same thing but with the top variable. Below these functions are two event handlers that specify which function to call when top and bottom are tapped. In its current state, nothing happens when you tap on the rectangle. In this puzzle, you’ll complete the animations inside of the functions so the rectangle animates when it’s tapped.

To complete the puzzle, attach .attr('fill', randomColor) to .duration(2000) inside the changeTop and changeBottom functions. Now, when you tap on the top or bottom of the rectangle, its color value will change.

Sample code solution:
(Tap below to reveal)

function changeBottom () {
    let randomColor = d3.rgb(pickRandom(255), pickRandom(255), pickRandom(255));
    bottom.transition().duration(2000).attr('fill', randomColor)

function changeTop () {
    let randomColor = d3.rgb(pickRandom(255), pickRandom(255), pickRandom(255));
    top.transition().duration(2000).attr('fill', randomColor)

bottom.on('click', changeBottom)
top.on('click', changeTop)

Javascript Concepts: Variable, Event Handlers, Function Declaration
D3 Concepts: Attribute, .transition(), .duration()
Additional Code:

let bottom = svg.append('rect').attr('width', '160').attr('height', '70').attr('fill', 'rgb(255,112,54)').attr('x', -70).attr('y',40)
let top = svg.append('rect').attr('width', '160').attr('height', '135').attr('fill', 'rgb(248,169,51)').attr('x', -70).attr('y',-100)

listed #2