D3 Tooltips with Interrupted Transitions

Posted on 16 January 2015 by Andrei Taraschuk

At Mobile System 7 we extensively use D3 Javascript Library in all of our data visualization components. Whenever a complex data structure is depicted we use tooltips to provide additional context. In this post I show how to build a simple tooltip with fade transitions. Let's get started!

First create a tooltip element and hide it by default (opacity = 0).

 var tooltip = d3.select('body').append('div')
     .attr('class', 'my-tooltip-class')
     .style('opacity', 0);

Next, wire in mouse events to show and hide the tooltip. Note that we are using transition.delay() to prevent the tooltip from showing immediately upon mouse over.

.on('mouseover', function (d) {
    tooltip.style('opacity', 0);
    tooltip.transition().delay(300).duration(500).style('opacity', 0.9);
})

Lastly, in the 'mouseout' event we need to interrupt (remove) any existing transitions and delays in the queue, then hide the tooltip. Keep in mind that unless the transition is interrupted the tooltip will still be displayed after the delay.

.on('mouseout', function () {
        tooltip.interrupt().transition();
        tooltip.style('opacity', 0);
 });

Here's the complete code:

var tooltip = d3.select("body").append("div")
            .attr("class", "my-tooltip-class")
            .style("opacity", 0),

    svg = d3.select('body').append("svg")
            .attr("width", 50)
            .attr("height", 50)
            .append("g").attr("transform", "translate(0,0)");

    svg.append("rect")
        .attr("x", 0).attr("y", 0)
        .attr("width", 100).attr("height", 100).attr("fill", 'red')
        .on("mouseout", function () {
            tooltip.interrupt().transition();
            tooltip.style("opacity", 0);
        })
        .on("mouseover", function () {
            tooltip.style("opacity", 0);

            // Note that we are also using d3.event pageX and pageY properties
            // to position the tooltip

            tooltip.html('Hello world')
                .style("left", (d3.event.pageX) + "px")
                .style("top", (d3.event.pageY - 25) + "px");

            tooltip.transition().delay(300).duration(500).style("opacity", 0.9);
        });

Copyright © 2014 Mobile System 7 - www.mobilesystem7.com