Skip to content

Instantly share code, notes, and snippets.

@curran
Last active August 29, 2015 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save curran/3afbcaab896f658754c9 to your computer and use it in GitHub Desktop.
Save curran/3afbcaab896f658754c9 to your computer and use it in GitHub Desktop.
D3 Links Example

This example shows how to make several SVG elements link to different things by constructing URLs from data properties. Each square links to a different Wikipedia page, and the link URL is generated dynamically from the data array.

This has the expected behavior of normal links when you open it in a new window. Clicking the rectangle doesn't work correctly in the bl.ocks viewer, because it is in an iFrame (open the debugging console to see the iFrame-related error), but this technique of adding links to visual marks should work fine in your own D3 projects.

This is addressing the thread Hyperlinks - error "undefined"/ NaN in the D3 Google Group.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>D3 Links Example</title>
<script src="//cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
</head>
<body>
<script>
var data = ["JavaScript", "Document_Object_Model", "Ajax_(programming)"];
d3.select("body").append("svg")
.attr("width", 960)
.attr("height", 500)
.selectAll("a").data(data)
.enter()
.append("a")
.attr("xlink:href", function (d){
return "http://en.wikipedia.org/wiki/" + d;
})
.append("rect")
.attr("x", function (d, i){
return 140 + i * 240;
})
.attr("y", 150)
.attr("width", 200)
.attr("height", 200);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment