Horizontal Tree

A Horizontal D3 Tree with collapsible nodes

by Alexander Tymchuk

HTML

<!-- <script src="https://d3js.org/d3.v3.min.js"></script> -->
<!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.8.0/d3.js"></script> -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.js"></script>
<div id="tree"></div>

SCSS

.node {
    cursor: pointer;
    circle {
      fill: #aae;
      /* stroke: steelblue;*/
      stroke-width: 2px;
    }
}

.node rect {
  fill: white;
  stroke-width: 1px;
}

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

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

.tree {
  margin-bottom: 10px;
  overflow: auto;
}

JavaScript

$(document).ready(function () {
            //build tree
            function BuildHorizontalTree(treeData, treeContainerDom) {
                var margin = { top: 40, right: 40, bottom: 20, left: 50 };
                var width = 960 - margin.right - margin.left;
                var height = 400 - 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.y, d.x]; });
                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),
                        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.y0 + "," + source.x0 + ")";
                        }).on("click", nodeclick);
                    nodeEnter.append("circle")
                     .attr("r", 10)
                        .attr("stroke", function (d) { return d.children || d._children ?...