score:4

Accepted answer

You will first have to label selection like this

text = vis.selectAll("text.label")    
     .data(nodes);

   // Enter any new label
    text.enter()
        .append("text")
        .attr("class", "label")
        .text(function(d) { return d.name; });
  //remove text for collapsed nodes.
  text.exit().remove();  

Then in the ticks function handle the text move (This is what you were missing as a result of which your text was coming fixed)

function tick() {
  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; });

  node.attr("cx", function(d) { return d.x; })
      .attr("cy", function(d) { return d.y; });
  //this will handle the label move
  text.attr("transform", function(d){ return "translate("+d.x+","+d.y+")"; });    
}

working example here

Hope this helps!


Related Query

More Query from same tag