Konstantin Hadzhiev
Konstantin Hadzhiev

Reputation: 195

Position of tree after node expansion

I recently took up D3 for a project, and i am facing an issue with the tree layout. When i initially load the tree layout it stays nicely within the SVG, as seen on the screenshot below. Initial state of tree when no nodes are opened

However, once i start opening the nodes, the more nodes i open, the more start going up and thus become invisible, as seen on the images below.

When i start opening nodes: When i start opening nodes When all nodes are opened: All of the nodes are opened.

As you can see i have made the svg scrollable vertically so that i can see bigger trees.

Here is how i create the tree layout:

var tree = d3.layout.tree()
         .nodeSize([55,30]);

Right now I found a solution by increasing the height of the 'g' element which holds all the nodes every time i click on a node that has children, but it is not a good solution because this causes the whole tree to "jump" every time this happens.

//creates the <g> element
var gWidth = 90;
var gHeight = 250;   
var vis = svg.append("g")
            .attr('id', 'group')
            .attr("transform", "translate(" + gWidth + "," + gHeight + ")");


function updateSvg(node){
 //moves the g element 50px down on each click that has a child
                  if(node.children){
                    gHeight +=50;
                    vis.attr("transform", "translate(" + gWidth + "," + gHeight + ")");
                   }
                   else{
                    gHeight-=50;
                    vis.attr("transform", "translate(" + gWidth + "," + gHeight + ")");
                  // }

}

I am also increasing the SVG height if there are more than a certain amount of nodes, but i think this is out of scope for my current issue.

Is there something I am missing?

Upvotes: 2

Views: 246

Answers (1)

tarulen
tarulen

Reputation: 2100

I can see two ways of trying to solve this:

1. Scroll your container automatically to avoid the jump, in your solution with the gHeight variable:

  document.getElementById("container").scrollTop += 50;

I am really not sure of this, though, so I think you'll do better with:

2. Use d3 zoom & pan methods The zoom behavior works pretty well, see

https://github.com/mbostock/d3/wiki/Zoom-Behavior

It boils down to

var zoom = d3.behavior.zoom();
svg.call(zoom);

and so you can get rid of the scrollbars and gHeights, and basically don't have to worry anymore about the window boundaries.

Upvotes: 1

Related Questions