Click here to Skip to main content
15,888,113 members
Articles / Programming Languages / Javascript
Tip/Trick

Creating Vertical Collapsible Tree With d3.js

Rate me:
Please Sign up or sign in to vote.
4.47/5 (6 votes)
25 Aug 2015CPOL 44.5K   7   3
Turn horizontal d3 tree to vertical

Introduction

Let's make a vertical collapsible tree using d3.js.

Styles

CSS
<style>
        .node {
            cursor: pointer;
        }

            .node circle {
                stroke-width: 3px;
            }

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

        .link {
            fill: none;
            stroke: #ccc;
            stroke-width: 2px;
        }

        .tree {
            margin-bottom: 10px;
            overflow: auto;
        }
    </style>

HTML

HTML
<script src="Scripts/jquery-1.8.2.js"></script>
 <script src="http://d3js.org/d3.v3.min.js"></script>

 <div id="tree">

  </div>

JS

JavaScript
$(document).ready(function () {
          //build tree
          function BuildVerticaLTree(treeData, treeContainerDom) {
              var margin = { top: 40, right: 120, bottom: 20, left: 120 };
              var width = 960 - margin.right - margin.left;
              var height = 500 - margin.top - margin.bottom;

              var i = 0, duration = 750;
              var tree = d3.layout.tree()
                  .size([height, width]);
              var diagonal = d3.svg.diagonal()
                  .projection(function (d) { return [d.x, d.y]; });
              var svg = d3.select(treeContainerDom).append("svg")
                  .attr("width", width + margin.right + margin.left)
                  .attr("height", height + margin.top + margin.bottom)
                .append("g")
                  .attr("transform", "translate
                  (" + margin.left + "," + margin.top + ")");
              root = treeData;

              update(root);
              function update(source) {
                  // Compute the new tree layout.
                  var nodes = tree.nodes(root).reverse(),
                      links = tree.links(nodes);
                  // Normalize for fixed-depth.
                  nodes.forEach(function (d) { d.y = d.depth * 100; });
                  // Declare the nodes…
                  var node = svg.selectAll("g.node")
                      .data(nodes, function (d) { return d.id || (d.id = ++i); });
                  // Enter the nodes.
                  var nodeEnter = node.enter().append("g")
                      .attr("class", "node")
                      .attr("transform", function (d) {
                          return "translate(" + source.x0 + "," + source.y0 + ")";
                      }).on("click", nodeclick);
                  nodeEnter.append("circle")
                   .attr("r", 10)
                      .attr("stroke", function (d)
                      { return d.children || d._children ?
                      "steelblue" : "#00c13f"; })
                      .style("fill", function (d)
                      { return d.children || d._children ?
                      "lightsteelblue" : "#fff"; });
                  //.attr("r", 10)
                  //.style("fill", "#fff");
                  nodeEnter.append("text")
                      .attr("y", function (d) {
                          return d.children || d._children ? -18 : 18;
                      })
                      .attr("dy", ".35em")
                      .attr("text-anchor", "middle")
                      .text(function (d) { return d.name; })
                      .style("fill-opacity", 1e-6);
                  // Transition nodes to their new position.
                  //horizontal tree
                  var nodeUpdate = node.transition()
                      .duration(duration)
                      .attr("transform", function (d)
                      { return "translate(" + d.x +
                      "," + d.y + ")"; });
                  nodeUpdate.select("circle")
                      .attr("r", 10)
                      .style("fill", function (d)
                      { return d._children ? "lightsteelblue" : "#fff"; });
                  nodeUpdate.select("text")
                      .style("fill-opacity", 1);

                  // Transition exiting nodes to the parent's new position.
                  var nodeExit = node.exit().transition()
                      .duration(duration)
                      .attr("transform", function (d)
                      { return "translate(" + source.x +
                      "," + source.y + ")"; })
                      .remove();
                  nodeExit.select("circle")
                      .attr("r", 1e-6);
                  nodeExit.select("text")
                      .style("fill-opacity", 1e-6);
                  // Update the links…
                  // Declare the links…
                  var link = svg.selectAll("path.link")
                      .data(links, function (d) { return d.target.id; });
                  // Enter the links.
                  link.enter().insert("path", "g")
                      .attr("class", "link")

                      .attr("d", function (d) {
                          var o = { x: source.x0, y: source.y0 };
                          return diagonal({ source: o, target: o });
                      });
                  // Transition links to their new position.
                  link.transition()
                      .duration(duration)
                  .attr("d", diagonal);

                  // Transition exiting nodes to the parent's new position.
                  link.exit().transition()
                      .duration(duration)
                      .attr("d", function (d) {
                          var o = { x: source.x, y: source.y };
                          return diagonal({ source: o, target: o });
                      })
                      .remove();

                  // Stash the old positions for transition.
                  nodes.forEach(function (d) {
                      d.x0 = d.x;
                      d.y0 = d.y;
                  });
              }

              // Toggle children on click.
              function nodeclick(d) {
                  if (d.children) {
                      d._children = d.children;
                      d.children = null;
                  } else {
                      d.children = d._children;
                      d._children = null;
                  }
                  update(d);
              }
          }

          var treeData =
      {
          "name": "Top Level",
          "parent": "null",
          "children": [
            {
                "name": "Level 2: A",
                "parent": "Top Level",
                "children": [
                  {
                      "name": "Son of A",
                      "parent": "Level 2: A",
                       "children": []
                  },
                  {
                      "name": "Daughter of A",
                      "parent": "Level 2: A",
                      "children": []
                  }
                ]
            },
            {
                "name": "Level 2: B",
                "parent": "Top Level",
                "children": []
            }
          ]
      };
          BuildVerticaLTree(treeData, "#tree");
      });

Output

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionNodes are Invisible Pin
Member 1223142617-May-16 20:55
Member 1223142617-May-16 20:55 
QuestionHow to add Node data in this tree Pin
Member 1223142617-May-16 19:51
Member 1223142617-May-16 19:51 
GeneralMy vote of 1 Pin
gicalle7526-Aug-15 3:19
professionalgicalle7526-Aug-15 3:19 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.