Skip to content

Instantly share code, notes, and snippets.

@curran
Last active August 29, 2015 14:21
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/88d03aa54097367eaae1 to your computer and use it in GitHub Desktop.
Save curran/88d03aa54097367eaae1 to your computer and use it in GitHub Desktop.
href on d3 objects

This example shows how to make an SVG element link to an external page.

This has the expected behavior of normal links when you open it in a new window. When clicked, the link will open in the current tab. When clicked while holding the meta key ("Command" on Macs and "Control" on Windows), the link will open in a new tab.

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 href on d3 objects in the D3 Google Group.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>D3 Link Example</title>
<script src="//cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
</head>
<body>
<script>
d3.select("body").append("svg")
.attr("width", 960)
.attr("height", 500)
.append("a")
.attr("xlink:href", "http://www.google.com")
.append("rect")
.attr("x", 280)
.attr("y", 50)
.attr("width", 400)
.attr("height", 400);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment