Hyperlinks in d3.js objects

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 rects 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.

Leave a Comment