Search code examples
javascriptd3.jstooltipstacked-chart

Why are my tooltips in d3 not updating correctly?


I'm using this jsfiddle. All of the tooltips are initially correct when I hover over the bars. But when I click the weekview button to change the graph the tooltips don't get updated.

I believe the problem is in this section:

layer.enter()
    .append("g")
    .attr("class", "layer");

layer.attr("fill", function (d, i) {
    return color(i);
    })
.append("svg:title")
.text(function(d){  
    return d[0].s;
});

layer.exit()
    .remove();

The append text is where I add the tooltips. I thought the enter and exit would refresh the bars and therefore refresh the tooltips but it isn't doing it correctly.

How do I update the tooltips when my graph changes?


Solution

  • It is because you are appending a new <title> element every time the bars change. The append should be done once on the enter selection and then simply update the value of the title in the update selection.

    Here's a modified version of your code with some comments inline (I've removed the parts that aren't relevant to the tool tip):

    layer.enter()
        .append("g")
        .attr("class", "layer")
            .append("title");  // add new element under new layer
    
    // add or update the value of the title element
    layer.select("title").text(function(d) {  
        return d[0].s;
    });