Zum Inhalt springen

Lektion 31 · Transitions and Interaction

Mouse Events and Tooltips

Handle click, hover and touch in D3 with selection.on and d3.pointer, build HTML tooltips, highlight marks, and add a crosshair to a line chart with bisect.

Interactivity is what separates an explorable chart from a picture. D3 does not invent its own event system: selection.on() is a thin wrapper around the browser's addEventListener. What D3 adds are helpers: d3.pointer() to turn an event into coordinates in the right space, d3.bisector() to find the data point nearest to the mouse, and a consistent signature (event, d) for listeners.

Adding listeners

JavaScript
circles.on("mouseenter", (event, d) => { /* ... */ });
circles.on("click", (event, d) => console.log(d));
circles.on("mouseleave", null);       // remove a listener

The listener receives the DOM event first and the datum second (D3 v6 and later; older tutorials show function(d) and the global d3.event, which no longer exist). this is the element when you use a regular function, not an arrow function.

Useful event names:

  • mouseenter / mouseleave: do not bubble, ideal for "hover" on a single mark.
  • mouseover / mouseout: bubble from children; they fire again when moving between child elements.
  • mousemove: fires continuously, good for tooltips that follow the pointer.
  • click, dblclick, contextmenu.
  • pointerenter, pointermove, pointerdown ... the pointer events, which unify mouse, touch and pen. Prefer them for new code.
  • focus and keydown for keyboard access (see Accessibility).

Where is the pointer? d3.pointer

event.clientX is relative to the browser window, which is rarely what you need. d3.pointer(event, target) returns [x, y] in the coordinate system of target, correctly accounting for SVG transforms, margins and scrolling. With no target it uses the event's current target.

JavaScript
svg.on("pointermove", event => {
  const [mx, my] = d3.pointer(event);          // relative to the SVG
  const [gx, gy] = d3.pointer(event, g.node()); // relative to a transformed <g>
});

Passing the translated plot group avoids subtracting margins by hand.

A tooltip with a hover highlight

The simplest tooltip is an absolutely-positioned HTML div. HTML gives you wrapping text, styling and the ability to use CSS transitions.

Hover tooltip on a scatter plot

Key details: the tooltip has pointer-events: none so it never steals the hover from the circle underneath (that would cause flicker), and it is positioned relative to a wrapper with position: relative. Using .html() with text from your data is safe only when you control or escape that text; for untrusted values use .text() on child elements.

Hovering a line chart: bisector and crosshair

Hovering tiny points is easy. Hovering a line needs another idea: listen on the whole plot area and find the data point nearest to the pointer's x position. d3.bisector(accessor).center does a binary search for it.

Line chart with a crosshair

Notice attr("pointer-events", "all") on a transparent rectangle: SVG shapes with fill="none" do not catch events unless this is set. x.invert() converts a pixel back into a data value, and bisector.center returns the index of the closest point (while .left and .right return insertion points).

flowchart LR
  P["pointermove event"] --> A["d3.pointer: pixel x"]
  A --> B["scale.invert: data x"]
  B --> C["bisector.center: nearest index"]
  C --> D["move crosshair and label"]

From pixel to data point in four steps.

Touch devices

Hover does not exist on touch screens. Pointer events fire on tap and on finger drag, so pointermove on a plot area works. Make sure targets are large enough (at least about 24 CSS pixels), show tooltips on tap, and add touch-action: none to the SVG if you drag inside it, otherwise the page scrolls instead.

Common mistakes

  • Using old signatures: .on("click", function(d) {...}) gives you the event, not the datum, in D3 v6+.
  • Using an arrow function and then reading this.
  • Using mouseover for tooltips on groups: it fires repeatedly as you cross children. Use mouseenter.
  • Positioning an HTML tooltip with event.pageX inside an embedded iframe or scrolled container; use d3.pointer(event, wrapper) instead.
  • Forgetting pointer-events on overlay rectangles or tooltips.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. What are the arguments of a D3 v7 listener added with selection.on?

    Since D3 v6 the event is passed first and the datum second. d3.event no longer exists.
  2. 2. Why give a tooltip div pointer-events: none?

    If the tooltip sits under the cursor it receives the events and the mark under it gets a mouseleave.
  3. 3. What does d3.bisector(d => d.day).center return?

    center does a binary search and returns the nearest index, ideal for hover on lines.
  4. 4. Which function converts a pixel coordinate back to a data value?

    invert is the inverse of the scale for continuous scales.

Summary

  • selection.on(type, (event, d) => ...) attaches listeners; use pointer events for mouse and touch.
  • d3.pointer(event, target) gives coordinates in the target's coordinate system.
  • HTML tooltips need pointer-events: none and a positioned wrapper.
  • scale.invert and d3.bisector(...).center find the nearest data point for lines and crosshairs.

Next: Brushing, Zooming and Dragging

Verfolge deinen Fortschritt

Erstelle ein kostenloses Konto, hake Lektionen ab und mach auf jedem Gerät dort weiter, wo du aufgehört hast.