carvil
carvil

Reputation: 199

How to include links in a D3 visualisation's text element?

I am trying to add a link to the text elements of this D3 visualisation:

http://bl.ocks.org/1093025

I would like to be able to click on "flare", "analytics" and navigate to another page or click in the rectangle and perform the normal action, which is expanding the sub-trees.

I tried a few things that didn't work:

I tried to add an on event to the svg:text element:

nodeEnter.append("svg:text")
  .attr("dy", 3.5)
  .attr("dx", 5.5)
  .text(function(d) { return d.name; })
  .on("click",function(d,i) { alert("Clicked on the text");});

I tried to add the foreignObject element like this:

 nodeEnter.append("svg:foreignObject")
  .style("float","right")
  .attr("height", 100)
  .attr("width", 100)
  .append("div")
  .html("<a href='#'>link</a>")

Even though it creates the link, it is an extra link, though (not the text element in the rectangle).

Finally, I also tried the following (in some combinations):

<a xlink:href="/svg/index.html">
    <text x="10" y="20">/svg/index.html</text>
</a>

But it didn't work either.

Any suggestions?

Upvotes: 4

Views: 9951

Answers (2)

Gecko 101
Gecko 101

Reputation: 91

I agree with Matt's answer re: pointer-events... change this to pointer-events: all in the css.

And this is how I made the link in the force directed graph:

svg = d3.select("body").append("svg");

svg.selectAll(".node")
  .append("svg:a").attr("xlink:href", function(d){ return "generic.php?url=" + d.url })
  .append("svg:text")
  .text(function(d) { return d.name; })
  .attr("dy", 3.5)
  .attr("dx", 5.5)
  .attr("text-anchor", "middle");
  //The End ;-)

Upvotes: 9

Matt Esch
Matt Esch

Reputation: 22956

.on('click', function () {}) should work as long as you

  • have selected the right nodes
  • haven't disabled pointer events on text elements with css

The pointer events seems to be catching people out as quite a lot of the examples have pointer-events: none for the text nodes.

Upvotes: 4

Related Questions