mheavers
mheavers

Reputation: 30158

d3.js tree diagram - expand only next level nodes when clicking on root node

I have a tree diagram I'm trying to adapt here, but the problem is that it automatically expands all root nodes in the tree when I click on a collapsed node, rather than just expanding the immediate children. Here's a fiddle. How do I resolve this?

http://jsfiddle.net/heaversm/nw577/

The function for handling the toggling / collapsing of the nodes:

function toggleChildren(d) {
    if (d.children) {
        d._children = d.children;
        d.children = null;
    } else if (d._children) {
        d.children = d._children;
        d._children = null;
    }
    return d;
}

Upvotes: 1

Views: 4239

Answers (1)

Lars Kotthoff
Lars Kotthoff

Reputation: 109232

The problem is that all nodes start expanded and only the state of an individual node is toggled on click. That is, all nodes underneath the root are still expanded, but not shown. As soon as you click the root node, they are. So they are not expanded as well as the root, but they were never collapsed.

To fix, just collapse all nodes to start with:

tree.nodes(root).forEach(function(n) { toggle(n); });

Complete demo here.

Upvotes: 1

Related Questions