Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append <div> to node in SVG with D3

Tags:

d3.js

I have tried to add some popup messages next to nodes but it looks like anything other than SVG <text> elements won't display with append.

This works:

  node.append("text")
      .attr("dx", 16)
      .attr("dy", ".0em")
      .text(function(d) { return d.name });

But when I append a div instead of text it is not visible. Is there something I am missing here? How can I make the div visible?

Also how can I easily get the position of node so i can transfer the positioning attributes to another element.

like image 406
BlitzCrank Avatar asked Jul 04 '12 05:07

BlitzCrank


2 Answers

You can't put HTML elements anywhere in an SVG, you need to enclose them in a foreignObject element, see here. If you enclose both the text element and the foreignObject in an SVG group (g element) and set the position on that, they should both show up in the same place without the need to set the same position on both.

like image 60
Lars Kotthoff Avatar answered Sep 28 '22 18:09

Lars Kotthoff


Alternatively, you can define your html code outside of svg in its' own div. Then append the contents by class using:

d3.select("#nytg-tooltip").style('top',ypos+"px").style('left',xpos+"px").style('display','block');

As seen in this example:

http://www.nytimes.com/interactive/2012/10/15/us/politics/swing-history.html?_r=0

enter image description here

like image 31
jonincanada Avatar answered Sep 28 '22 20:09

jonincanada