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.pageX
or d3.select(this)
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. Used in the above example. Code looks like that:
tooltip
.style("top", (event.pageY)+"px")
.style("left",(event.pageX)+"px")
Note that you can add a numeric value next to event.pageX
or Y to adjust the tooltip position
d3.select(this)
is the 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")
Note: It can sometimes be quite a pain to position tooltips if you have a complex layout in your webpage. For instance, this post uses the bootstrap framework to build columns. Thus the event.pageY()
position must be corrected.
ToDo: Dig here to understand this problem more in depth