Lastly, we add a tooltip to our timeline. We talk about how to add a listener rectangle, d3.leastIndex(), and how to add a dot to mark our place.
Let's go through one last example for adding tooltips. So far, we've added tooltips to individual elements (bars, circles, and paths). Adding a tooltip to a timeline is a bit different.
In this section, we're aiming to add a tooltip to our line chart like this:
Instead of catching hover events for individual elements, we want to display a tooltip whenever a user is hovering anywhere on the chart. Therefore, we'll want an element that spans our entire bounds.
To start coding up our Set up interactions step, let's create a
<rect> that covers our bounds and add our mouse event listeners to it. This time we'll want to listen for
mousemove events instead of
mouseenter events because we'll want to update the tooltip's position when a reader moves their mouse around the chart.
Note that we don't need to define our
yattributes because they both default to
Perfect! We can see that our
listeningRect, defaulted to a black fill, covers our entire bounds.
Let's add a rule to
styles.css so we can see our chart again.
Great! Now we can set up our
tooltip variable and
onMouseLeave() functions (back in our
Let's start fleshing out
onMouseMove — how will we know the location on our line that we are hovering over? The passed parameters we used previously (
nodes) won't be helpful here, and
this will just point us at the listener rect element.
When an event listener is invoked, the d3-selection library sets a global
d3.event will refer to the currently triggered event and will be reset when the event listener is done. During the event listener handler, we also get access to a
d3.mouse() function which will return the
y coordinates of the mouse event, relative to a specified container.
Let's see what that would look like in action and pass our listener container to
Now we can see our mouse position as an
[x,y] array when we move our mouse around the chart.
Test it out — what do the numbers look like when you hover over the top left of the chart? What about the bottom right?
Thankfully, d3 scales make this very simple! We can use the same
xScale() we've used previously, which has an
.invert() will convert our units backwards, from the
range to the
Let's pass the x position of our mouse (
mousePosition) to the
.invert() method of our