score:0

I think that I have found the solution, I am studing this example Modifying a Force Layout (thanks).

And this is my implementation:

<!DOCTYPE html>
<meta charset="utf-8">
<style>
    .link {
        stroke: #000;
        stroke-width: 1.5px;
    }

    .node {
        fill: #000;
        stroke: #fff;
        stroke-width: 1.5px;
    }
</style>
<body>
<script src="http://d3js.org/d3.v3.js"></script>
<script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
<script>

var width = 960;
var height = 500;

var color = d3.scale.category20();

var nodes = [];
var links = [];

var force = d3.layout.force()
    .nodes(nodes)
    .links(links)
    .charge(-400)
    .linkDistance(120)
    .size([width, height])
    .on("tick", tick);

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height);

var node = svg.selectAll(".node");
var link = svg.selectAll(".link");

var a = {id: "a"}, b = {id: "b"}, c = {id: "c"};
nodes.push(a, b, c);
links.push({source: a, target: b}, {source: a, target: c});
repaint();

var d = {id: "d"}
nodes.push(d);
links.push({source: a, target: d}, {source: b, target: d});
repaint();

var e = {id: "e"}
nodes.push(e);
links.push({source: d, target: e});
repaint();

var f = {id: "f"}
nodes.push(f);
links.push({source: f, target: d});
repaint();

ajax();

function repaint() {
    link = link.data(force.links(), function(d) { return d.source.id + "-" + d.target.id; });
    link.enter().insert("line", ".node").attr("class", "link");
    link.exit().remove();

    node = node.data(force.nodes(), function(d) { return d.id;});
    node.enter().append("circle").attr("class", function(d) { return "node " + d.id; }).attr("r", 8).style("fill", function(d) { return color(d.id); });
    node.exit().remove();

    force.start();
}

function ajax() {
    jQuery.ajax({
        url: "no_exists.html",
        timeout: 5000,
        success: function() {
            setTimeout(function(){ajax();}, 2000);
            create_random_node();
        },
        error: function() {
            setTimeout(function(){ajax();}, 2000);
            create_random_node();
        }
    });
}

function create_random_node() {
    var id = Math.random().toString(36).substring(2);
    var temp_node = {"id": id};

    nodes.push(temp_node);
    links.push({
        source: nodes[Math.floor(Math.random() * nodes.length)],
        target: temp_node});

    repaint();
}

function tick() {
    node.attr("cx", function(d) { return d.x; })
        .attr("cy", function(d) { return d.y; })

    link.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; });
}

</script>

Related Query

More Query from same tag