How To Highlight Path From Root To Selected Node In D3 Js?
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 highl
Solution 1:
First make a flatten function which will make the hierarchical data into a n array.
functionflatten(root) {
var nodes = [],
i = 0;
functionrecurse(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 selectvar select = d3.select("select").node().value;
//find selected data from flattened root recordvar find = flatten(root).find(function(d) {
if (d.name == select)
returntrue;
});
//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 rootwhile (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.
Post a Comment for "How To Highlight Path From Root To Selected Node In D3 Js?"