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?
First make a flatten function which will make the hierarchical data into an 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 .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.