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.
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.
Rewrite it with delegation: one listener on the svg. What changes when a click lands on the background?
Explain it without notes
What arguments does a D3 7 listener receive?
Why does a listener added with addEventListener run three times after three draw calls, but one added with on run once?
When is event delegation better than a listener per bar?
Preview
Console
Nothing logged yet.Expected console output
pointer at 100 50
pointer at 5 115