Reputation: 9918
I have applied clustered dendrogram to show an organization's structure. It works well. In addition, I want to add links to the node texts.
I have added "url" keys to the json array for each node
{
"name": "Institutes",
"children": [
{ "name": "Social", "url": "http://social.example.com/" },
{ "name": "Health", "url": "http://health.example.com/" },
{ "name": "Nature", "url": "http://nature.example.com/" },
{ "name": "Education", "url": "http://social.example.com/" }
]
}
There are two problems:
<a>
tags do not wrap all the <text>
element. it is displayed as <a></a><text></text>
. I want it to be <a><text></text></a>
.
How can I read url
key from json in order to add it as href
attribute's value (see the line with comment //???
) ?
d3.json("org_chart.json", function(error, root) {
var nodes = cluster.nodes(root),
links = cluster.links(nodes);
var link = svg.selectAll(".link")
.data(links)
.enter().append("path")
.attr("class", "link")
.attr("d", diagonal);
var node = svg.selectAll(".node")
.data(nodes)
.enter().append("g")
.attr("class", "node")
.attr("transform", function(d) {
return "translate(" + d.y + "," + d.x + ")";
});
node.append("circle")
.attr("r", 5.1);
node.append("a")
.attr("href", "#") //???
.attr("target","_blank");
node.append("text")
.attr("dx", function(d) {
return d.children ? -9 : 8;
})
.attr("dy", 3)
.style("text-anchor", function(d) {
return d.children ? "end" : "start";
})
.text(function(d) {
return d.name;
});
});
One more thing:
I have tried
node.append("a").attr("href", function (d) { return d.url;});
and it returns undefined
. Also I have tried
node.append("a").attr("href", "http://example.com");
Although it looks like
<g class="node" transform="translate(0,428.74692874692875)">
<circle r="5.1"></circle>
<a href="http://example.com/" target="_blank">
<text dx="-9" dy="3" style="text-anchor: end;">
Education
</text>
</a>
</g>
it does not open http://example.com when I click on it.
Upvotes: 0
Views: 358
Reputation: 9359
When you're using selection.append(name)
it returns a new selection containing the appended elements, so you can just do another append directly to it, like so:
node.append("a").append("text");
In order to obtain the url
property you need to use an accessor function, like so:
node.append("a").attr("href", function (d) {
return d.url;
});
Edit:
For links you might need to import the xlink namespace in your html file:
<html xmlns:xlink="http://www.w3.org/1999/xlink">
And use namespacing:
.append("svg:a").attr("xlink:href", urlAccessor)
See relevant answer here.
Upvotes: 1