D3.js: Position tooltips using element position, not mouse position?

Richard picture Richard · Apr 27, 2013 · Viewed 60.5k times · Source

I'm using D3 to draw a scatter graph. I would like to show tooltips when the user mouses over each circle.

My problem is that I can append tooltips, but they're positioned using the mouse event d3.event.pageX and d3.event.pageY, so they are not positioned consistently over each circle.

Instead, some are slightly to the left of the circle, some to the right - it depends on how the user's mouse enters the circle.

This is my code:

circles
  .on("mouseover", function(d) {         
    tooltip.html(d)  
      .style("left", (d3.event.pageX) + "px")     
      .style("top", (d3.event.pageY - 28) + "px");    
  })                  
  .on("mouseout", function(d) {       
    tooltip.transition().duration(500).style("opacity", 0);   
  });

And is a JSFiddle showing the problem: http://jsfiddle.net/WLYUY/5/

Is there some way I can use the centre of the circle itself as the position to orient the tooltip, not the mouse position?

Answer

Lars Kotthoff picture Lars Kotthoff · Apr 27, 2013

In your particular case you can simply use d to position the tooltip, i.e.

tooltip.html(d)  
  .style("left", d + "px")     
  .style("top", d + "px");

To make this a bit more general, you can select the element that is being moused over and get its coordinates to position the tooltip, i.e.

tooltip.html(d)  
  .style("left", d3.select(this).attr("cx") + "px")     
  .style("top", d3.select(this).attr("cy") + "px");