chris loughnane
chris loughnane

Reputation: 2738

D3 Tree Layout: I want to use jQuery to toggle all children

I'm using this example as a base: http://mbostock.github.io/d3/talk/20111018/tree.html

In my code I start with all nodes collapsed and a user can click branches to navigate the tree as in the demo.

For user convenience I would like to use jQuery to toggle expand/collapse all children of the root. The code below will only toggle the immediate children of the root.

I've tried many options but I can't work out the correct function. Any help would be appreciated.

$('.clicktoexpandALL').click(function(){
    toggle(root);
    update(root);
});

I have tried toggle(root.children[0]) & toggle(root.children[1].children[2]); to no avail.

EDIT: UPDATED Question.

If I could access the toggleAll(d) function I'd be able to do what I want but a simple function call wont work.

d3.json("json/results.json", function(json) { root = json; root.x0 = h / 2; root.y0 = 0;

function toggleAll(d) {
  if (d.children) {
    d.children.forEach(toggleAll);
    toggle(d);
  }
}

// Initialize the display to hide nodes.
root.children.forEach(toggleAll);

update(root);

});

ADDED JSFIDDLE LINKS

with code http://jsfiddle.net/chrisloughnane/vV3Sc/

full screen http://jsfiddle.net/chrisloughnane/vV3Sc/show/

Upvotes: 1

Views: 1663

Answers (1)

Pablo Navarro
Pablo Navarro

Reputation: 8264

I think that you need to use the method toggleAll, which toggle the root node and the sub nodes under it:

function toggleAll(d) {
  if (d.children) {
    d.children.forEach(toggleAll);
    toggle(d);
  }
}

The toggle method will hide/show the attribute children of the root, but not the children of other nodes.

Upvotes: 1

Related Questions