d3 graphing test

just testing out the d3 js framework

by edwardsharp

HTML

<script src="http://d3js.org/d3.v2.js"></script>
<form>
    <input type="button" value="Graph" id="graph_submit"/>
</form>
<div id="chart"><div></div></div>

CSS

.link line { stroke: #32CD32; stroke-width: 2; }

JavaScript

var data_nodes, data_links, svg_nodes, svg_links, svg_root;

// array for chart size [width, height]
var chart_size = [];

chart_size.push(600);
chart_size.push(600);

// create new force directed graph
var force = d3.layout.force()
              .size(chart_size)
              .linkDistance(150)
              .charge(-1000)
              .friction(0.3);

// set tick handler for force graph animation
force.on("tick", function() {

      // all links get an x and y coordinate for their end points
      svg_root.selectAll('g.link line')
              .attr("x1", function(d) { return d.source.x; })
              .attr("y1", function(d) { return d.source.y; })
              .attr("x2", function(d) { return d.target.x; })
              .attr("y2", function(d) { return d.target.y; });

       // all nodes get a SVG transform attribute 
       // http://www.w3.org/TR/SVG/coords.html#TransformAttribute
       svg_root.selectAll('g.node')
               .attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });
});


$('#graph_submit').click(function(event) {

   // remove inner div
   d3.select("#chart div").remove();

   // create new inner div and svg element with a configurable size
   svg_root = d3.select("#chart")
                .append("div")
                .append("svg")
                .attr("width", chart_size[0])
                .attr("height", chart_size[1])
                .call(d3.behavior.zoom().on("zoom", redraw))
                .append("svg:g");

    // fill rect which is same size as while SVG element
    svg_root.append("svg:rect")
            .attr("width", chart_size[0])
            .attr("height", chart_size[1])
            .attr("fill", "#F2F0E3");
    
    // zoom handler
    function redraw() { svg_root.attr("transform", "translate(" + d3.event.translate + ") scale(" + d3.event.scale + ")"); }

    // start from scratch with empty nodes and links
    data_nodes = [{ "name": "ROOT" },{ "name": "NODE1" },{ "name": "NODE2"...