Search code examples
javascripthtmld3.jstooltipdata-visualization

How to show the tooltip on d3 force directed layout node?


I have built a sample d3 visualisation with the hierarchy data, which works very well.I need to display the data binded to that icon/node when the user move mouse across the node. I have done that too, which works well.

I need to display the data according to the node on the tooltip. i do not want to bind an html element for the same.

Here is my code

HTML:

  <div id="chart"></div>

JS:

 node = vis.selectAll(".node");
        node = node.data(force.nodes());
        node.exit().remove();
        node.enter().append("g")
            .attr("class", "node")
            .on("click", click).on("mouseover", function(){return tooltip.style("visibility", "visible") 
                 tooltip.text
                 ;})
.on("mousemove", function(){return tooltip.style("top",
    (d3.event.pageY - 130)+"px").style("left",(d3.event.pageX - 130 )+"px");})
.on("mouseout", function(){return tooltip.style("visibility", "hidden");});

APPLICATION ON FIDDLE


Solution

  • To add class to tooltip do:

    var tooltip = d3.select("#chart")
            .append("div")
            .attr("class", "my-tooltip")//add the tooltip class
            .style("position", "absolute")
            .style("z-index", "10")
            .style("visibility", "hidden");
        tooltip.append("div")
            .attr("id", "tt-name")
            .text("simple");
        tooltip.append("div")
            .attr("id", "tt-size")
            .text("simple");
    

    To add value and size on mouse hover do:

    tooltip.select("#tt-name").text(d.name)
    tooltip.select("#tt-size").text(d.size)
    

    Updated code is here: