Change selected style of nodes, d3.js resettable offset tree

I am trying to give the user a better idea of ​​where they are in the tree by highlighting the "selected" node in the tree and also displaying a plus / minus-like icon based on whether or not children are shown.

I can't seem to find anything on how to do this as it seems that after the tree is redrawn after expanding the selected node information will disappear and cannot be applied. Currently my tree nodes are highlighted based on whether children are hidden / shown or have no data, but I would like to keep track of which node was clicked with fill color. my tree is based on mbostocks block # 1093025. Any help would be greatly appreciated for toggling the plus / minus icon and also highlighting the selected node.

Current code for displaying expand / collapse icons:

nodeEnter.append("svg:image")
    .attr("xlink:href", function(d) {
        if (d._children) return "images/arrow_right.png";
        else if (d.children) return "images/arrow_left.png";
    })
    .attr("x", "-12px")
    .attr("y", "-10px")
    .attr("width", 15)
    .attr("width", 20);

      

Function to increase the selected node with functions to resize ... cannot make them work at all or recognize the selected node when redrawing. Only padding seems to recognize the selected node.

nodeEnter.append("rect")
    .attr("y", newy)
    .attr("height", newheight)
    .attr("width", barWidth)
    .style("fill", color)
    .on("click", click);

function newy(d) {
    if (d._isSelected)
        return -barHeight / 1.25;
    else
        return -barheight/2;
}
function newheight(d) {
    if (d._isSelected)
        return barHeight * 1.75;
    else
        return barheight;
}

      

+3


source to share


1 answer


Just because the example code "forgets" the selected node, doesn't mean you can't add it yourself:

// Toggle children on click.
var lastClickD = null;
function click(d) {
  if (d.children) {
    d._children = d.children;
    d.children = null;
  } else {
    d.children = d._children;
    d._children = null;
  }
  if (lastClickD){
    lastClickD._isSelected = false;
  }
  d._isSelected = true;
  lastClickD = d;
  update(d);
}

// on the selected one change color to red
function color(d) {
  if (d._isSelected) return 'red';
  return d._children ? "#3182bd" : d.children ? "#c6dbef" : "#fd8d3c";
}

      

To add expand / collapse indicators, simply update the nodes on redraw based on the state of the children:



// we used to set the text on enter
nodeEnter.append("text")
  .attr("dy", 3.5)
  .attr("dx", 5.5); 

// but now we change it on update based on children
node.select('text') 
  .text(function(d) { 
    if (d.children) {
      return '+' + d.name;
    } else if (d._children) {
      return '-' + d.name;
    } else {
      return d.name;
    }
  });

      

Here's an example .

+1


source







All Articles