Skip to content

Instantly share code, notes, and snippets.

@d3noob
Last active February 20, 2019 14:37
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save d3noob/87d9880fd5ae41b8fb5e309b59031002 to your computer and use it in GitHub Desktop.
Adding links to objects in v4

The above example is intended to demonstrate adding a hyperlink to an object (the rectangle) and instructing the text object to be transparent to the pointer so that the link on the rectangle is recognised 'through' the text.

This is one of the code samples for the update to the book D3 Tips and Tricks to version 4 of d3.js.

<!DOCTYPE html>
<meta charset="utf-8">
<body>
<!-- load the d3.js library -->
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
var width = 449;
var height = 249;
var word = "gongoozler";
var holder = d3.select("body")
.append("svg")
.attr("width", width)
.attr("height", height);
// draw a rectangle
holder.append("a")
.attr("xlink:href", "http://en.wikipedia.org/wiki/"+word)
.append("rect")
.attr("x", 100)
.attr("y", 50)
.attr("height", 100)
.attr("width", 200)
.style("fill", "lightgreen")
.attr("rx", 10)
.attr("ry", 10);
// draw text on the screen
holder.append("text")
.attr("x", 200)
.attr("y", 100)
.style("fill", "black")
.style("font-size", "20px")
.attr("dy", ".35em")
.attr("text-anchor", "middle")
.style("pointer-events", "none")
.text(word);
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment