Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 431
Richard Avatar asked Apr 27 '13 20:04

Richard


People also ask

What are tooltips in D3 JS?

Tooltips are a feature designers can use when they want to gradually reveal information to users as they hover or place keyboard focus over an element. In this guide, you will learn two approaches to enhancing your D3.js charts by implementing tooltips.

How to recover the mouse position when the tooltip changes?

Two different functions allow to recover the mouse position and use it to control the tooltip position. event.pageX () and event.pageY (). Recover the mouse position when the event happens.

What is the difference between mouseout and MouseMove in D3?

mouseout is used to hide the tooltip once the mouse is out of the Element. mousemove is used to move the tooltip with the mouse. d3. select ('svg'). selectAll ('circle'). data (data). join ('circle'). attr ('r', 3). on ('mouseover', function (e) { }). on ('mouseout', function (e) { }). on ('mousemove', function (e) { })

Why do we use the mouse position?

Why? We use the mouse position to change the position of the tooltip with d3.event but it gives you the absolute position of the mouse on the screen not within your SVG. We also set the position of the element to absolute so that it is outside of the flow of the document and can overlap other elements.


Video Answer


1 Answers

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"); 
like image 108
Lars Kotthoff Avatar answered Oct 05 '22 02:10

Lars Kotthoff