Search code examples
javascriptcssd3.jstreeview

Overriding the CSS causes D3JS tree path link to be visible after node expansion or collapse


I have code similar to the example in this plunkr. I am trying to override the ".link" entry in the CSS to download as SVG document.

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

The problem is that once I do that, the links are not removed on node expansion or collapse.

I commented the class attribute in the original code and inserted the attributes in the following function:

// Update the linksâ¦
var link = svg.selectAll("path.link")
   .data(links, function (d) {
      return d.target.id;
});

// Enter any new links at the parent's previous position.
link.enter().append("path", "g")
   //.attr("class", "link")
   .attr("stroke", "#ccc")
   .attr("fill", "none")
   .attr("stroke-width", "2px")
   .attr("x", boxWidth )
   .attr("y", boxHeight)
   .attr("d", function (d) {
     console.log(source)
   var o = {
       x: source.x0,
       y: source.y0
   };
   return diagonal({
       source: o,
       target: o
   });

});

Any insight as to why this behavior is occurring?


Solution

  • Your original code is:

    var link = svg.selectAll("path.link")
      ...
    
    link.enter()
      .append("path")
      .attr("class","link")
      ...
    

    If you remove the class of the appended items, then every time you draw the tree the first selection (link) will be empty (because there are no paths with class link). So, any links in the data array will be entered. This is why the code works as expected initially. However, no link will ever be updated or exited because there are no elements in the selection to either update or exit - the selection will always be empty.

    If these are your only paths, you could change the selection selector to be:

     var link = svg.selectAll("path")
       ...
    

    Eg.

    Or, alternatively, you could keep the class associated with the elements, but remove any css styling associated with that class. In either event, you'd apply the styling properties with .attr() still, as you have done.