0

I would like to show a text on mouseover.

var circle = elemEnter.append("circle")
          .attr("r", function(d){return d.r*2} )
          .attr("dx", function(d){return d.x} )
          .attr("stroke","gray")
          .attr("fill", "#91c6ed")
          .on("mouseover", function()
                          {d3.select(this).style("stroke", "#ff7f0e");
               d3.select(this).style("stroke-width", "2px");
               elemEnter.append("text")
                        .text(function(d){return d.name})})
          .on("mouseout", function()
                          {d3.select(this).style("stroke", "gray");
                           d3.select(this).style("stroke-width", "1px");});

This piece of code works but show all the names on all the circles and when I try to replace

elemEnter.append("text").text(function(d){return d.name})

by

d3.select(this).append("text").text(d.name)

nothing happens.

I think it is possible to do it but I don't know what I'm doing wrong.

Valram
  • 125
  • 7
  • 1
    Do you want a tooltip? [This answer](http://stackoverflow.com/questions/10805184/d3-show-data-on-mouseover-of-circle/10806220#10806220) should help. – Lars Kotthoff May 07 '13 at 17:02
  • why do you not use the function in the second example? '.text( func...)' – cmonkey May 07 '13 at 17:10

1 Answers1

2

You can't append text to a circle. You need to start with a g and append the circle to the g and append the text to the g. Keep in mind that the g will not have cx/cy attributes and so you'll need to put that data into the following syntax:

.attr("transform", function (d) {return "translate("+d.X+","+d.Y")"})

If you're binding data, bind it to the g and then just naked append the circle and text to the g.

Oleg
  • 9,341
  • 2
  • 43
  • 58
Elijah
  • 4,609
  • 3
  • 28
  • 36