Hyperlinks in D3.js Objects, Part 2

I am very new to D3, but I have compiled a Reingold-Tilford tree based on this example: http://bl.ocks.org/mbostock/4339184

I am trying to add hyperlinks to every child element of a node that terminates one of the chains - basically, any node that has a whitish circle in front of it.

I found this useful explanation of how to add hyperlinks - Hyperlinks in d3.js objects - but, unfortunately, I understand only half of this.

The author writes:

It's pretty simple, just add a few more “keys”: value pairs. Example:

"children": [ { "name": "Google", "size": 3938, "url": "https://www.google.com" }, { "name": "Bing", "size": 3938, "url": "http://www.bing.com" } ] 

I agree, it's easy - I did it. But after I did this, how can I change the page code, as the helper added in this other post, "in the d3 drawing code, where you add nodes for each data item, you wrap the item you want interactive links with svg : tag: "

 nodeEnter.append("svg:a") .attr("xlink:href", function(d){return d.url;}) // <-- reading the new "url" property .append("svg:rect") .attr("y", -barHeight / 2) .attr("height", barHeight) .attr("width", barWidth) .style("fill", color) .on("click", click); // <- remove this if you like 

This is what I do not understand. Can someone explain how I need to change this to align the text in this example - http://bl.ocks.org/mbostock/4339184

Thanks in advance.

Matt

0
source share
1 answer

First you will need to check if the node you have has children, so you can distinguish which links will be and which ones will be text. After that you can add the correct item. Therefore, instead of adding only the text elements that you are currently doing:

 node.append("text") .attr("dx", function(d) { return d.children ? -8 : 8; }) .attr("dy", 3) .attr("text-anchor", function(d) { return d.children ? "end" : "start"; }) .text(function(d) { return d.name; }); 

Turn them over, determine who has the children, and add the correct element accordingly:

 node.each(function(d){ var thisNode = d3.select(this); if (!d.children) { thisNode.append("a") .attr("xlink:href", function(d) { return d.url; }) .append("text") .attr("dx", 8) .attr("dy", 3) .attr("text-anchor", "start") .text(function(d) { return d.name; }); } else { thisNode.append("text") .attr("dx", -8) .attr("dy", 3) .attr("text-anchor", "end") .text(function(d) { return d.name; }); } }); 

Now only nodes that do not have children will be linked by hyperlinks. FYI: As you can see, I forgot some redundant functions that were tested only for children, since you already know if the node has one, you will no longer need it.

+1
source

Source: https://habr.com/ru/post/979746/


All Articles