This is document gives a few insights on how to add tooltips with d3.js. It is composed by several interactive examples, allowing to play with the code to understand better how it works.
.svg
. Note that it would work the same with any type of svg
element.div
is added, with a bit of text in it and a few features. It is actually the tooltip! But it is hidden is css with visibility: hidden
.
html
html
element in your tooltip. Thus, absolutely any customization is doable.
event.offsetX
or d3.select(this)
There are a number of different ways to recover the mouse position and use it to control the tooltip position.
event.offsetX
and event.offsetY
are properties of MouseEvent. They provide the mouse position when the event happens. Used in the above example. The code looks like this:
tooltip
.style("top", (event.offsetY)+"px")
.style("left",(event.offsetX)+"px")
You can add a numeric value next to event.offsetX
or Y to adjust the tooltip position
Note: As well as event.offsetX
, MouseEvent provides a number of other position properties like pageX
, screenX
and clientX
. See here for more information about the differences between these.
d3.select(this)
is a second option. It selects the element that is hovered. Thus, it is possible to get whatever attribute or style of this element, like its position. If the element is a circle, you can get the cx
attribute, which is the horizontal positioning.
tooltip
.style("top", d3.select(this).attr("cy") + "px");
.style("left", d3.select(this).attr("cx") + "px")
d3.mouse(this)
another option. Not sure of the differences with 2 others above.
tooltip
.style("top", (d3.mouse(this)[1]) + "px")
.style("left", (d3.mouse(this)[0]) + "px")