Collapse / expand child tree nodes in d3.js?

I am building a tree structure (or rather, modifying one of the examples with a set of my own data in my own json), and I'm trying to create some functions:

My tree layout is an example of a tree: http://mbostock.github.com/d3/ex/cluster.html

I add (in circles) the onclick event, which I would like to collapse the children of the clicked node. That is, when the user clicks on the steel blue circle associated with the node, I want the child nodes to disappear.

I looked through the documentation and I did not find anything that would allow me to make the nodes collapse or disappear.

What can I do?

+7
source share
3 answers

Unfortunately, I still have not dealt with D3, and I do not know how to best answer your question. But here is a power oriented layout that allows you to show / hide nodes by clicking on them, which may give you some ideas: http://bl.ocks.org/1062288

+1
source

There a couple fits, you just need to use regular styling to hide the markup for children (opacity: 0 or display: none). However, this simply makes the data invisible, the tree retains its shape, as if the data were there, you simply cannot see them.

Usually you need the tree to pretend that there is no data there, and update accordingly, for this you can use the same approach as the example of the layout with forced orientation in the above link.

It comes down to: 1) Use the function to build the d3 tree 2) add a click event to collapsible nodes 3) The click event renames the child property of the node and calls the function in 1), which redraws the tree without these node children.

Here is the corresponding code from the link in nkoren answer ( http://bl.ocks.org/1062288 ):

function update() { // build the tree layout here // append on("click", click) to the collapsible nodes } // Toggle children on click function click(d) { if (d.children) { d._children = d.children; d.children = null; } else { d.children = d._children; d._children = null; } update(); } 
+1
source

All Articles