I have created a tree using d3 js. Now i have created a drop-down menu containing list of all the nodes in the tree. Now on selecting a node from the drop down menu,i want to highlight path from root to that particular node. How to do this?
Asked
Active
Viewed 3,378 times
1 Answers
1
First make a flatten function which will make the hierarchical data into a n array.
function flatten(root) {
var nodes = [],
i = 0;
function recurse(node) {
if (node.children) node.children.forEach(recurse);
if (node._children) node._children.forEach(recurse);
if (!node.id) node.id = ++i;
nodes.push(node);
}
recurse(root);
return nodes;
}
On the select box add a change listener like this:
var select = d3.select("body")
.append("select")
.on("change", function() {
//get the value of the select
var select = d3.select("select").node().value;
//find selected data from flattened root record
var find = flatten(root).find(function(d) {
if (d.name == select)
return true;
});
//reset all the data to have color undefined.
flatten(root).forEach(function(d) {
d.color = undefined;
})
//iterate over the selected node and set color as red.
//till it reaches it reaches the root
while (find.parent) {
find.color = "red";
find = find.parent;
}
update(find);//call update to reflect the color change
});
Inside your update function color the path according to the data (set in the select function) like this:
d3.selectAll("path").style("stroke", function(d) {
if (d.target.color) {
return d.target.color;//if the value is set
} else {
return "gray"
}
})
Working code here.

halfer
- 19,824
- 17
- 99
- 186

Cyril Cherian
- 32,177
- 7
- 46
- 55
-
if a collapsed node is selected from the drop down menu...the path is highlighted internally,but that full path should also be expanded and on clicking on reset button ,the tree should reset to original.................Anyways,Thank you so very much for helping me :) – Jason May 22 '16 at 05:43
-
1See you asked the question. I answered it. You increased the scope. I still answered it. You just cant make me do a project for you LOL... Ask complete clear question, don't go expanding the scope. If someone answers it accept it. If you have new question ask a new question in SO. – Cyril Cherian May 22 '16 at 06:04
-
Ok cyril,Thanks a lot....i am not expanding the scope actually,that is what i initially wanted and that is quite logical....accepting your answer :) .....thanks a lot....would be really nice if you could help me further...Here's the new question http://stackoverflow.com/questions/37370444/highlight-and-un-highlight-path-from-selected-node-to-root-node-in-a-collapsible – Jason May 22 '16 at 06:10
-
1diagonal() is no longer supported in d4 v4 :/ – Mar 12 '17 at 16:45