Manish Agrawal
Manish Agrawal

Reputation: 794

D3.js collapsible tree - expand/collapse nodes

I have a D3.js collapsible tree which has a bunch of nodes as like shown in below figure enter image description here

Now I want to collapse all other node if a node is expanded. For example in figure if analytics node is expanded then it should collapse data node. I am refering D3.js collapsible tree - expand/collapse intermediate nodes but its not much helpful.

Upvotes: 3

Views: 2209

Answers (2)

Manish Agrawal
Manish Agrawal

Reputation: 794

I got the solution with the help of Przemek hint. Now it working perfectly. :)

function click(d) {
var index;
for(var i=0;i<d.parent.children.length;i++){//length of current label
    if(d.parent.children[i].name===d.name)
        index = i;
};

for(var i=0;i<d.parent.children.length;i++){
    if(typeof d.parent.children[i].children!=="undefined" && i!=index){//if child is expnd then make null
        d.parent.children[i]._children=d.parent.children[i].children;
        d.parent.children[i].children= null;
    }
}
if (d.children) {
    d._children = d.children;
    d.children = null;
} else {
    d.children = d._children;
    d._children = null;
}
update(d);
}

Upvotes: 0

Przemek
Przemek

Reputation: 803

Change click function to this

function click(d) {
    for (var i = 0; i < d.parent.children.length; i++) {
        if (d.parent.children[i].name !== d.name) {

            console.log(d.parent.children[i])

            if (d.parent.children[i].children) {
                d.parent.children[i].children = d._children;
                d.parent.children[i].children = null;
            }           
        }
    };

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

    update(d);
}

Hope it helps

Upvotes: 1

Related Questions