Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 5.6 — Events in D3
Data Visualization · Example 3 of 3

Pointer coordinates

d3.pointer subtracts the SVG's position on the page, so the numbers are the same wherever the chart sits.

selection.on("click", (event, d) => ...) attaches a listener to every selected mark, and gives it the browser's event and the mark's datum. Learn the version 7 form, how to remove listeners, why re-running draw must not stack them, and when one listener on the parent beats one per mark.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write a draw(rows) that makes bars and a click listener that writes the station name into #name. Make sure calling it three times leaves one listener per bar.

02

Rewrite it with delegation: one listener on the svg. What changes when a click lands on the background?

Explain it without notes

01

What arguments does a D3 7 listener receive?

02

Why does a listener added with addEventListener run three times after three draw calls, but one added with on run once?

03

When is event delegation better than a listener per bar?

Pointer coordinates

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

pointer at 100 50
pointer at 5 115