We learn how to add interaction event listeners using our d3 selection objects, then run through a concrete example.
Browsers have native event listeners — using
addEventListener(), we can listen for events from a user's:
... and more.
After running this code, the browser will trigger
onClick() when a user clicks anywhere on the page.
These event listeners have tons of functionality and are simple to use. We can get even more functionality using d3's event listener wrappers!
Our d3 selection objects have an
.on() method that will create event listeners on our selected DOM elements. Let's take a look at how to implement d3 event listeners.
If we open the
events.js file, we can see a few things happening:
rectColorsas an array of colors.
We grab all
.rectelements inside of the
#svgelement (created in
index.html) and bind our selection to the
.join()to isolate all new data points (every row in
rectColors) and append a
<rect>for each color.
Lastly, we set each
<rect>'s size to 100 pixels by 100 pixels and shift each item 110 pixels to the right (multiplied by its index). We also make all of our boxes light grey.
In our browser, we can see our four boxes.
They don't do much right now, let's make it so they change to their designated color on hover.