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 p
In my experience, the easist solution is as follows:
First, getBoundingClientRect()
to get the position of your element.
Then, use window.pageYOffset
to adjust the height, relative to where you are.
E.g.
.on('mouseover', function(d) {
let pos = d3.select(this).node().getBoundingClientRect();
d3.select('#tooltip')
.style('left', `${pos['x']}px`)
.style('top', `${(window.pageYOffset + pos['y'] - 100)}px`);
})
In the example above, I don't use X's offset because we rarely need to (unless you're scrolling horizontally).
Adding window.pageYOffset
and pos['y']
gives us the current mouse position (wherever we are on the page). I subtract 100 to place the tooltip a little above it.