Search code examples
d3.jstooltip

How to add hover (tooltip) to the D3. bubble motion chart?


I am using the template of the motion chart in D3 to create something similar. It works, but I need to do more work on it. One thing is to show the tooltip that contains all of x , y, and radius info in it. I want the tooltip to show up when the mouse moves over each bubble. Does anyone know how to do that? Thank you. The source page you can find at https://github.com/mbostock/bost.ocks.org/blob/gh-pages/mike/nations/index.html

Here is what I did:

    var tooltip = d3.select("body")
    .append("div")
    .style("position", "absolute")
    .style("z-index", "10")
    .style("visibility", "hidden")
    .text("a simple tooltip");

    tooltip.text("my tooltip text");

    var dots = svg.append("g")
        .attr("class", "dots");

    var dot = dots.selectAll(".dot")
        .data(interpolateData(1990))
        .enter().append("circle")
        .attr("class", "dot")
        .style("fill", function (d) {
            return colorScale(color(d));
        })
        .on("mouseover", function(d){return tooltip.style("visibility", "visible");})
        .on("mousemove", function(d){return tooltip.style("top",(d3.event.pageY-10)+"px").style("left",(d3.event.pageX+10)+"px");})
        .on("mouseout", function (d){return tooltip.style("visibility", "hidden");})

Solution

  • You're trying to mix SVG and HTML, which is probably not the best idea in the world. The answer that Lars linked to uses SVG's built-in title, which shows up as a tooltip.

    You can easily accomplish this in your chart, by adding these calls after .call(position):

    .append('svg:title')
    .text(function(d) { return d.name; });
    

    If you insist on mixing HTML into the SVG mix, you can set the tooltip.text from inside your mouseover event handler:

    .on("mouseover", function(d){ 
      tooltip.text(d.name); 
      return tooltip.style("visibility", "visible");
    })
    

    This jsbin contains both approaches: http://jsbin.com/zexiz/2/edit?js,output