This video is available to students only

Adding the tooltip

Onto our last step: adding interactions! The tooltip we'll build will be unlike any you've seen before - it will follow the mouse all the way around our chart, highlight the relevant data elements, and describe the weather for that hovered date.

Now for the fun part: adding interactions! Although our viewers can orient themselves to the different parts of our chart, we also want them to be able to dig in and view details about a particular day.

Let's add a tooltip that shows up when the user hovered anywhere over the chart. We'll want to start by adding a listener element that covers our whole chart and initializing our mouse move events.

Perfect, the black area covers exactly where we want any movement to trigger a tooltip.

Chart with listener circle

Let's hide our listener by making its fill transparent.

Next, we'll need to create our tooltip element in our index.html file, with a spot for each of our hovered over day's metrics to be displayed.

Let's also add our tooltip styles in our styles.css file, remembering to hide our tooltip and to give our wrapper a position to create a new context.

Switching back in our chart.js file, we'll want to grab our tooltip element to reference later, and also make a <path> element to highlight the hovered over day.

Now we can fill out our onMouseMove() function. Let's start by grabbing the x and y position of our cursor, using d3.pointer().

We have our mouse position, but we need to know the angle from the chart origin. How do we convert from an [x, y] position to an angle? We'll need to use an inverse trigonometric function: atan2. If you're curious, read more about atan2 here.

Remember that these trigonometric functions originate around the horizontal, right plane of our circle. Let's rotate the resulting angle back one-quarter turn around the circle to match our date scale.

To keep our angles positive, we'll want to rotate any negative angles around our circle by one full turn, so they fit on our angleScale.

We want to draw a line to highlight the date we're hovering, but it needs to increase in width as it gets farther from the center of our circle. To create this shape, we'll use d3.arc(), which is the arc version of the line generators we've been using (d3.line()). We can use the .innerRadius() and outerRadius() methods to tell it how long we want our arc to be, and the .startAngle() and .endAngle() methods to tell it how wide we want our arc to be.


This page is a preview of Fullstack D3 Masterclass

Start a new discussion. All notification go to the author.