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?
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.
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.
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? 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.
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With