praks5432
praks5432

Reputation: 7792

D3.js appending svg/dom element not working

So I'm trying to append a dom or svg element to a circle(the latter to avoid the foreign object thing). I'm doing this

        var tooltip  = d3.select(this).append("text")
            .attr("class", "tooltip")
            .text("HELLO")
            .attr('x', 1000)
            .attr('y', 1000);

Where this is the circle svg element.

However, this doesn't work -

enter image description here

But I can't see an effect on the webpage.

Why?

Upvotes: 1

Views: 4685

Answers (2)

Reyraa
Reyraa

Reputation: 4294

if you want to move or animate or locate some svg elements together, you need to create a group element and append all of those to the group.

<g>
   <circle cx="20" cy="20" r="20" fill="green" />
   <circle cx="70" cy="70" r="20" fill="purple" />
</g>

then you can add attributes that goes for all of them:

<g stroke="black" stroke-width="2" fill="#fff">

and the "transform" is an available attribute too:

<g transform="translate(80,0)">
   <circle cx="20" cy="20" r="20" fill="green" />
   <circle cx="70" cy="70" r="20" fill="purple" />
</g>

but if you're working with damn D3.js, you need to append it with svg namespace.

var tooltip  = d3.append('svg:g').append("svg:text")
            .attr("class", "tooltip")
            .text("HELLO")
            .attr('x', 1000)
            .attr('y', 1000);
tooltip.append('svg:circle').attr('fill','#f00');

Upvotes: 1

Lars Kotthoff
Lars Kotthoff

Reputation: 109292

In SVG, you can't append text element to circle elements -- the specification doesn't allow that. Append them to g elements or the top-level SVG, otherwise they won't be displayed.

Upvotes: 1

Related Questions