An event listener waits for a specified event, then runs a callback. In a visualization, that callback connects an action—such as clicking a filter or entering a data point with the mouse—to a visible chart update. JavaScript provides addEventListener(); D3 provides on() for attaching listeners to a selection. section 7.2.1 section 7.0
Use selection.on("click", (e, d) => { ... }) to listen for clicks. The first argument to on() names the event; the second is the callback. Inside the callback, e is the DOM event and d is the datum attached to the element that received it. Inspect e.target to find that element, or use the datum directly to decide what to change. Other event names include mouseover, touch, and keydown. section 7.2.1
Click a histogram filter
Attach a click listener to each filter button. When a button is clicked, first check whether its datum is already active. If not, update the filters’ active values, change the buttons’ active classes, and call updateHistogram() with the selected filter ID. Skipping an already active button avoids an unnecessary chart update. section 7.2.1
Listing 7.2 Handling the active state (interactions.js)
...
.on("click", (e, d) => {
if (!d.isActive) { #1
filters.forEach(filter => { #2
filter.isActive = d.id === filter.id ?
true : false;
});
d3.selectAll(".filter") #3
.classed("active", filter => filter.id ===
d.id ? true : false);
updateHistogram(d.id, data); #4
}
});
The complete click callback shows how the clicked button’s datum drives both its visible active state and the histogram update. section 7.2.1
Choose the event and callback actions to match the interaction:
- For a line-chart tooltip, listen for mouseenter and mouseleave on the data circles. On entry, read the circle’s datum, position the tooltip above the event target, and reveal it; on exit, hide it. section 7.3.1
- For responsive labels, listen for window resize, read the new window width, and run the same resizeChart() function used on page load. section 9.2.1
- When a data update adds new chart elements, attach listeners to those entering elements too. section 7.4.3
A listener can also coordinate several interface elements. In a circle pack, mouseenter on a language circle or its label fills an information panel from the attached data, hides the instructions, and shows the panel. Mouseleave reverses that display. Consider the input device: small circles can make touch interaction difficult on mobile screens. section 11.2.3























