I am a complete novice at d3.js or java in general. I am using the indented tree example from http://bl.ocks.org/1093025. It took me two hours to get this to work on my local computer, so that should give you an idea of my skill level.
I opened the flare.json file and started messing with it and was able to manipulate it successfully. It looks like this
{ "name": "Test D3", "children": [ { "name": "News", "children": [ { "name": "CNN", "size": 1000 }, { "name": "BBC", "size": 3812 } ] }, { "name": "Blogs", "children": [ { "name": "Engaget", "size": 3938 } ] }, { "name": "Search", "children": [ { "name": "Google", "size": 3938 }, { "name": "Bing", "size": 3938 } ] } ] }
What I want to do now, is to try to add hyperlinks. For example, I want to be able to click on "CNN" and go to CNN.com. Is there a modification I can make to flare.json that will do that?
It is quite easy, just add some more "key" : "value" pairs. Example:
"children": [ { "name": "Google", "size": 3938, "url": "https://www.google.com" }, { "name": "Bing", "size": 3938, "url": "http://www.bing.com" } ]
Of course, in your d3 code you then need to append
<svg:a>
tags and set their xlink:href
attribute.
Here is some html and d3-code that might be of help to you. First you need to import the xlink namespace in your html file:
<html xmlns:xlink="http://www.w3.org/1999/xlink"> ... </html>
Then in the d3 drawing code where you append nodes for each data element you wrap the element you want to be clickable links with an svg:a
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
You might want to remove the click handler (which is present in the original example) by deleting the .on("click", click) as it might interfere with the default behavior of SVG links.
Clicking on your rect
s should now lead you to the appropriate url
. SVG links might not be fully implemented in all browsers.
Alternatively you could modify the click
handler to read the URL from d.url
and use that one to manually redirect the browser to that URL via JavaScript: window.location = d.url;
. Then you do not need the svg:a
tag and the xlink
code. Though adding a real link (not a scripted one) has the benefit that the user/browser can decide what to do (e.g., open in new tab/page). It also helps if some of your users have JavaScript disabled.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With