Jason
Jason

Reputation: 786

How to display rectangular div with data on mouse over event of any node in d3 js tree?

I have created a tree using d3 js. Now i on mouse over any node,a rectangular box containing node name and id should be displayed. I tried this

But this does not work on mouse over any node.How to do this?

Upvotes: 3

Views: 1580

Answers (1)

Gerardo Furtado
Gerardo Furtado

Reputation: 102218

You cannot append HTML elements (div, p, h1, h2 etc) to a SVG. The tag can even show up when you inspect the DOM, but it simply doesn't work.

This is what you can do:

First, set the CSS style for the tooltip, using a div with a class named "tooltip":

div.tooltip {   
    position: absolute;         
    text-align: /*whatever*/;           
    white-space: /*whatever*/;                  
    padding: /*whatever*/;              
    font-size: /*whatever*/;        
    background: /*whatever*/;   
    border: /*whatever*/;   
    border-radius: /*whatever*/;            
    pointer-events: /*whatever*/;
    etc...          
}

Then set a tooltip var (here, #svgId is the Id of the element where you append your svg, not much different of selecting "body" as you did):

var tooltip = d3.select("#svgId").append("div") 
            .attr("class", "tooltip")               
            .style("opacity", 0);

The div has 0 opacity. Then it's just a matter of showing the tooltip on mouseover or mousemove:

nodeEnter.on("mousemove", function(d) {
            tooltip.html("<strong> Look, I'm bold !</strong> and now I'm 
                    not bold <br> and this is another line! and this
                    is my data:" + d.whatever)
                    .style('top', d3.event.pageY - 12 + 'px')
                    .style('left', d3.event.pageX + 25 + 'px')
                    .style("opacity", 1);
        });

nodeEnter.on("mouseout", function(d) {
            tooltip.style("opacity", 0);
        });

PS: This is a list of SVG elements that you can append (without using foreignObject): http://www.w3schools.com/svg/svg_reference.asp

Upvotes: 5

Related Questions