0

I want to make a tree where the same thing can be listed multiple times, and on mouseover all of the same thing will expand or light up or something. What I can't figure out is how to do this. My initial thought was to use a line like

.attr("class", function(d){return d})

but that didn't seem to work. If anybody has any ideas about how to do this it would be much appreciated. The tree for example may look like

Food
  Vegtables
    Carrot
    Pizza
  Tastes good
    Cake
    Pizza

I would want to be able to make it so that if i hover over pizza once in my tree both of them will do the same on mouseover action.

Tom
  • 91
  • 4
  • 15
  • Ever try the jQuery.find() function? – Fallenreaper Jul 10 '12 at 20:12
  • I dont know jQuery (i know i should learn it), but i think what that function does is find all nodes with a certain class name. What I need to do is as make the tree make all nodes with the same name have the same class. So to reiterate, I am trying to give them class names, not find them. Does this do that? I am not sure. Thanks though – Tom Jul 10 '12 at 22:29

2 Answers2

4

Most likely your code didn't work because d is an object (representing a node in the tree), and the default to-string behavior for objects returns "[object Object]"; setting the class attribute to "[object Object]" won't help you select nodes by class.

You need to define the class attribute as a property of data. For example, if you data has a type property, then you could define the class attribute as

.attr("class", function(d) { return "node " + d.type; })

Next, register a mouseover and mouseout handler for interaction:

.on("mouseover", function(d) { highlight(d.type); })
.on("mouseout", function(d) { highlight(null); })

Finally, the highlight function selects nodes by class and toggles an active class which overrides the fill color.

function highlight(type) {
  if (type == null) d3.selectAll(".node").classed("active", false);
  else d3.selectAll(".node." + type).classed("active", true);
}

The active class is defined as:

.node.active {
  fill: red;
}

Live example here:

For more details on how to select related nodes, see my answer to how do you select (and then modify) related elements?

Community
  • 1
  • 1
mbostock
  • 51,423
  • 13
  • 175
  • 129
0

Your answer is simple. Firstly, you will need to have access to the root of your tree? Got it? Good. Now you will just call jQuery on it to find what you are looking for and then toggle a class. Example:

 $(root).find("pizza").hover(function(){
    $(this).toggleClass("colorChange");
 });

this is untested but if build correctly, would work

Fallenreaper
  • 10,222
  • 12
  • 66
  • 129