Collapsed D3 Tree

tree graph that begins collapsed and you can click the root node to start exploring the paths

by elvis reyes

HTML

<script src="http:////cdnjs.cloudflare.com/ajax/libs/d3/3.4.4/d3.min.js"></script>
<body>
     <div id="map"></div>
</body>

CSS

.node {
  cursor: pointer;
}

.node circle {
  fill: #fff;
  stroke: #f98415;
  stroke-width: 1.5px;
}

.node text {
  font: 12px sans-serif;
}

.link {
  fill: none;
  stroke: #ededed;
  stroke-width: 1.5px;
}
.tooltip {
  font-family: sans-serif;
  position: absolute;
  width: 20em;
  padding: 1em;
  font-size: 12px;
  background: #f8f8f8;
  border: 1px solid #ededed;
  border-radius: 8px;
  pointer-events: none;
}

JavaScript

var margin = {top: 30, right: 20, bottom: 30, left: 20},
    width = 960 - margin.left - margin.right,
    barHeight = 20,
    barWidth = width * .8;
var height = 500 - margin.top - margin.bottom;
var i = 0,
    duration = 400,
    root;

var tree = d3.layout.tree()
    .nodeSize([0, 20]);

var diagonal = d3.svg.diagonal()
    .projection(function(d) { return [d.y, d.x]; });

var svg = d3.select("body").append("svg")
    .attr("width", width + margin.left + margin.right)
  .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

var testjson = '{"name": "flare","children": [{"name": 2 ,"children": [{"name": "cluster","children": [{"name": "AgglomerativeCluster", "size": 3938},{"name": "CommunityStructure", "size": 3812}]},{"name": "graph","children": [{"name": "BetweennessCentrality", "redirect": 2}]}]}]}';
	
flare = JSON.parse(testjson);
flare.x0 = height / 2;
flare.y0 = 0;
  flare.x0 = 0;
  flare.y0 = 0;
  
   function collapse(d) {
		if (d.children) {
		  d._children = d.children;
		  d._children.forEach(collapse);
		  d.children = null;
		}
	  }
  
  
  
 flare.children.forEach(collapse);
  update(root = flare);



function update(source) {

  // Compute the flattened node list. TODO use d3.layout.hierarchy.
  var nodes = tree.nodes(root);
	console.log(nodes);
  var height = Math.max(500, nodes.length * barHeight + margin.top + margin.bottom);

  d3.select("svg").transition()
      .duration(duration)
      .attr("height", height);



  // Compute the "layout".
  nodes.forEach(function(n, i) {
    n.x = i * barHeight;
  });

  // Update the nodes…
  var node = svg.selectAll("g.node")
      .data(nodes, function(d) { return d.id || (d.id = ++i); });

  var nodeEnter = node.enter().append("g")
      .attr("class", "node")
      .attr("transform", function(d) { return "translate(" + source.y0 + "," + source.x0 + ")"; })
      .style("opacity", 1e-6);

  // Enter any new nodes at the parent's previous position.
 ...