This video is available to students only

d3 events

We learn how to add interaction event listeners using our d3 selection objects, then run through a concrete example.

d3 events#

Browsers have native event listeners — using addEventListener(), we can listen for events from a user's:

  • mouse

  • keyboard

  • scroll wheel

  • touch

  • resize

  • ... and more.

For example:

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:

  1. We define rectColors as an array of colors.

  2. We grab all .rect elements inside of the #svg element (created in index.html) and bind our selection to the rectColors array.

  3. We use .join() to isolate all new data points (every row in rectColors) and append a <rect> for each color.

  4. 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.

grey boxes

They don't do much right now, let's make it so they change to their designated color on hover.

 

This page is a preview of Fullstack D3 Masterclass

No discussions yet