Interaction and zooming
Bind D3 events, implement tooltips, and use zoom to add zooming and panning to charts.
🎯 Introduction
Charts can now render and animate. The next step is interaction: highlighting bars on hover, showing values in tooltips, and zooming with the mouse wheel are standard requirements in real projects. This article covers D3 event binding, tooltips, and zoom to make charts interactive.
🧱 Bind events with .on()
D3's .on() attaches event listeners to elements, much like JavaScript's native addEventListener:
svg.selectAll('rect').on('mouseenter', function (event, d) {
console.log(d); // { day: 'Mon', value: 120 }: the datum bound to this bar
});
The event callback receives two arguments:
event: The native browser event, containing information such as pointer position.d: The datum bound to this element. Hovering a bar gives you that bar's data.
To modify only the hovered bar, access it through this:
svg.selectAll('rect')
.on('mouseenter', function (event, d) {
d3.select(this).attr('fill', 'orange'); // Change only this bar
})
.on('mouseleave', function (event, d) {
d3.select(this).attr('fill', '#5470c6'); // Restore its color on leave
});
Two common pitfalls:
🎉 You now have the foundations of D3 interaction! Next, we will bring everything together in a reusable Vue 3 chart component.
- The arguments are
(event, d): event first, datum second. Older tutorials use(d, i), the signature from D3 v5 and earlier. Copying it into v7 gives you the wrong values. - To access the current element through
this, use a regularfunction, because arrow functions do not have their ownthis. :::
Hover over a bar to try it.
🛠 Implement a tooltip
A tooltip displays a small value card beside the pointer when a bar is hovered. Use an absolutely positioneddiv and coordinate three events:| Event | Responsibility |
|---|---|
mouseenter | Show the tooltip and populate its content |
mousemove | Move the tooltip with the pointer |
mouseleave | Hide the tooltip |
views/TooltipChart.vue
<template>
<div class="wrapper">
<svg ref="svgRef" class="chart"></svg>
<!-- Tooltip container, initially hidden -->
<div ref="tooltipRef" class="tooltip"></div>
</div>
</template>
<script setup>
import { onMounted, ref } from 'vue';
import * as d3 from 'd3';
const svgRef = ref(null);
const tooltipRef = ref(null);
onMounted(() => {
const svg = d3.select(svgRef.value);
const tooltip = d3.select(tooltipRef.value);
// Scales and bars are as in the previous example; omitted to focus on events
svg.selectAll('rect')
.on('mouseenter', function (event, d) {
tooltip.style('opacity', 1).text(`${d.day}: ${d.value}`); // Show the value
})
.on('mousemove', function (event, d) {
// Use offsetX/offsetY to position the tooltip below and right of the pointer
tooltip
.style('left', event.offsetX + 10 + 'px')
.style('top', event.offsetY + 10 + 'px');
})
.on('mouseleave', function (event, d) {
tooltip.style('opacity', 0); // Hide the tooltip
});
});
</script>
<style scoped>
.wrapper {
position: relative; /* Position the tooltip relative to this wrapper */
}
.tooltip {
position: absolute;
opacity: 0; /* Initially hidden */
pointer-events: none; /* Keep the tooltip from intercepting pointer events */
background: rgba(0, 0, 0, 0.7);
color: #fff;
padding: 4px 8px;
border-radius: 4px;
font-size: 12px;
}
</style>
pointer-events: none matters: without it, the tooltip can intercept the pointer and repeatedly trigger enter/leave events on the bar, causing flickering.Hover over the bars below to try the tooltip:🧱 d3.zoom: zooming and panning
With many data points or a large dashboard, users often need to zoom in with the wheel and drag to pan. D3'szoom supports these interactions directly:const g = svg.append('g'); // Draw all graphics inside this group
const zoom = d3
.zoom()
.scaleExtent([0.5, 8]) // Allow zoom scales from 0.5× to 8×
.on('zoom', event => {
g.attr('transform', event.transform); // Apply the zoom transform to the group
});
d3.select(svgRef.value).call(zoom);
zoom captures wheel and drag gestures and converts them into a transform containing translation and scale. Applying it to the graphics group pans and zooms the entire chart. Pinch-to-zoom and single-finger dragging on touch devices are supported automatically.Set
Try zooming with the wheel and dragging to pan this scatterplot:scaleExtent to prevent users from zooming out indefinitely until the chart disappears.Scroll to zoom and drag to pan (0.5× to 8×).
❓ Questions and answers
Q1: Why not use SVG's title element for tooltips?title provides a browser-native tooltip with limited styling and a display delay. A custom div gives you control over appearance, as in most chart libraries.Q2: Can click handlers access data?Yes. In .on('click', function (event, d) {}), d is the bound datum. For example, clicking a bar can open a detail page for that item.Q3: Will zooming also scale axis labels?Yes, if the axes are inside the transformed g. To keep labels at a consistent size, recalculate scales and redraw axes in the callback. That is an advanced topic; start by transforming the whole chart.Q4: Why is d undefined in my event handler?Check the callback argument order, especially when copying the old v5 (d, i) signature. In v7, use function (event, d). Arrow functions accept the same arguments, but cannot provide the current element through their own this.🧪 Exercise
Add interactions to the earlier bar chart:- Highlight hovered bars in orange and display the day and value in a tooltip.
- Make the tooltip follow the pointer and hide it when the pointer leaves.
- Add
d3.zoomwith a scale extent from 0.8 to 5.
svg.selectAll('rect')
.data(data)
.join('rect')
.attr('x', d => xScale(d.day))
.attr('y', d => yScale(d.value))
.attr('width', xScale.bandwidth())
.attr('height', d => height - yScale(d.value))
.attr('fill', '#5470c6');
// Write your code here (event listeners, tooltip, and zoom)
🎉 You now have the foundations of D3 interaction! Next, we will bring everything together in a reusable Vue 3 chart component.
