D3’s on() method registers an event listener on a selection. Pass an event name first and a callback function second; the callback runs whenever that event occurs. section 7.2.1
The event name can be any DOM event, including click, mouseover, touch, keydown, mouseenter, mouseleave, and mousemove. The callback receives the captured event e and the selected element’s datum d. section 7.2.1 section 7.3.1
d3.select("#filters")
.selectAll(".filter")
.data(filters)
.join("button")
.attr("class", d => `filter ${d.isActive ? "active" : ""}`)
.text(d => d.label)
.on("click", (e, d) => {
console.log("DOM event", e);
console.log("Attached datum", d);
});
A complete selection chain binds filter-button data to buttons and logs both the DOM event and attached datum when a button is clicked. section 7.2.1
Use the callback to connect interaction with a visible visualization change:
- Handle a filter button’s click, update active state with classed(), and redraw the histogram. section 7.2.1
- Reveal a temperature tooltip on mouseenter, position it from the event target, animate its opacity, and hide it on mouseleave. section 7.3.1
- Track mousemove over streamgraph paths, use d3.pointer(e) for position, and update tooltip content from the corresponding year. section 7.3.2
- Display hierarchical node details on mouseenter by reading attached data and hide them when the pointer leaves. section 11.2.3
Event-driven tooltip
Select chart circles and attach mouseenter and mouseleave listeners. On entry, format the datum’s average temperature, translate the tooltip above the circle, and transition its opacity to 1; on exit, set opacity to 0 and move it away. section 7.3.1
Keep interaction relevant and intuitive. Combine on() with selection methods such as classed(), transition(), d3.pointer(), and scale inversion when the response needs state, animation, coordinates, or data lookup. section 7.5 section 7.3.2
