nani1216
nani1216

Reputation: 324

Add custom html to nodes in d3 js tree

I'm trying to build a tree like d3 js tree. I need to add a div and 2 or 3 buttons in that div for each node of the tree. Clicking on that node button should show a popup.

I'm trying for this kind of functionality There are other plugins similar to this. But i need this in d3 js tree as its navigation and animations are smooth.

Upvotes: 1

Views: 5455

Answers (2)

Igor
Igor

Reputation: 181

You can use .append("svg:foreignObject") to add custom html to nodes in d3 js tree, for example jsfiddle example

Upvotes: 0

JuanCarniglia
JuanCarniglia

Reputation: 49

I have done this:

  • Use base example from D3 tree web page.
  • Added more SVG elements in the nodes
  • Added a "popup" menu when you click the node text (Add, Remove, Edit, Move) to perform this simple operations on the node.

In my experience, it is better to use SVG elements instead of a DIV (You can display buttons as images or shapes, and text as svg:text.

Here is some code:

function clickLabel(d) {

// this removes the popup if it was displayed on another node beforehand
// is=2 identifies markers... 

d3.selectAll("[marker='2']").remove();

// Every node has an ID, and I add shapes to it

d3.select("[id_node='" + d.id + "']")
    .append("image")
    .attr("marker", 2)
    .attr("xlink:href", "/Content/delete_item.png")
    .attr("x", 0)
    .attr("y", -50)
    .attr("height", 32)
    .attr("width", 32)
    .on("click", removeItem);

d3.select("[id_node='" + d.id + "']")
    .append("image")
    .attr("marker", 2)
    .attr("xlink:href", "/Content/edit.png")
    .attr("x", -50)
    .attr("y", -30)
    .attr("height", 32)
    .attr("width", 32)
    .on("click", editItem); 

d3.select("[id_node='" + d.id + "']")
    .append("image")
    .attr("marker", 2)
    .attr("xlink:href", "/Content/add_item.png")
    .attr("x", 20)
    .attr("y", 10)
    .attr("height", 32)
    .attr("width", 32)
    .on("click", addItem);


d3.select("[id_node='" + d.id + "']")
    .append("image")
    .attr("marker", 2)
    .attr("xlink:href", "/Content/next_item.png")
    .attr("x", -30)
    .attr("y", 20)
    .attr("height", 32)
    .attr("width", 32)
    .on("click", moveItem);

// Stop events or else it gets de-selected
event.stopPropagation();

}

Hope this helps!

Upvotes: 2

Related Questions