...

/

My Favorite Tooltip: The Final Block

My Favorite Tooltip: The Final Block

Understand the final block of code that projects a circle to the tooltip location.

Adding the circle to the graph

Adding the circle to the graph is actually fairly simple:

    focus.append("circle")
        .attr("class", "y")
        .style("fill", "none")
        .style("stroke", "blue")
        .attr("r", 4);

If you’ve followed any of the other examples in “D3 Tips and Tricks,” there shouldn’t be any surprises here (well, perhaps assigning a class to the circle (y) could count as mildly unusual).

But there is one small thing…

We don’t place it anywhere on the graph! There are no x, y coordinates and no translation of position. Nothing! Never fear; All we want to do at this stage is create the element. In a few blocks of code time, we will move the circle.

Set the area to capture the mouse movements

As we briefly covered earlier, the thing that makes this particular tooltip technique different is we don’t hover over an element to highlight the tooltip. Instead, we move the mouse into an area that is relevant to the tooltip and it appears.

And it’s all thanks to the following code:

  svg.append("rect")
      .attr("width", width)
      .attr("height", height)
      .style("fill", "none")
      .style("pointer-events", "all")
      .on("mouseover", function() { focus.style("display", null); })
      .on("mouseout", function() { focus.style("display", "none"); })
      .on("mousemove", mousemove);

Here, we’re adding a rectangle to the graph (svg.append("rect")) with the same ...