Question

I'm 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 functionality:

My tree's layout is that from the tree example: http://mbostock.github.com/d3/ex/cluster.html

I am adding (to the circles) an onclick event which I would like to collapse the children of the clicked node. That is to say, when a user clicks the steelblue circle associated with a node, I want that nodes children to disappear.

I've scoured the documentation and I haven't turned up anything which would allow me to make nodes collapse or disappear.

What could I do?

Was it helpful?

Solution

There's this:

http://mbostock.github.com/d3/talk/20111018/tree.html

There are a number of other interactive hierarchical layout examples from my SVG Open keynote.

OTHER TIPS

Unfortunately I'm still getting up to speed with D3, and am not sure how to best answer your question. But Here's a force-directed layout which allows you to show/hide nodes by clicking on them, which might give you some ideas: http://bl.ocks.org/1062288

There's a couple approaches, one is just to use regular stying to hide the markup of the children (opacity: 0, or display: none). However, this just makes the data invisible, the tree maintains its shape as if the data is there, you just can't see it.

Usually you'll want the tree to pretend the data isn't there and update accordingly, for that you can use the same approach as the force-directed layout example in the above link.

It boils down to: 1) Use a function to build the d3 tree 2) append a click event to the collapsible nodes 3) The click event renames the children property of the node and calls the function in 1) which redraws the tree without that node's children.

Here's the relevant code from the link in nkoren's 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();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top