Reputation: 648
I have a div tooltip that I would like to centre over SVG circles created using D3. My mouseover event triggers the div's 'hidden' class to false.
Because the div is hidden, I am unable to calculate it's width and am therefore unable to centre the div on the circle the way I would like:
var width = document.getElementById("tooltip").offsetWidth;
...
.style("left", xPosition - (width/2) + "px" )
Is there a way I can get around this?
Its probably worth noting that I don't want the div to have a fixed width.
var w = 300, h = 500;
var svg = d3.select('body').append('svg').attr('width', w).attr('height', h)
svg.append('circle').attr('r', 20)
.attr('cx', 200)
.attr('cy', 300)
.on("mouseover", function(d) {
var xPosition = parseFloat(d3.select(this).attr("cx"));
var yPosition = parseFloat(d3.select(this).attr("cy"));
var width = document.getElementById("tooltip").offsetWidth;
d3.select("#tooltip")
.style("left", xPosition - (width/2) + "px" )
.style("top", yPosition + "px")
.select("#value")
.text(d);
d3.select("#tooltip").classed("hidden", false);
})
.on("mouseout", function() {
d3.select("#tooltip").classed("hidden", true);
})
Upvotes: 0
Views: 66
Reputation: 3144
You have to first give the div
a display value other than "none". Then you get its width. Then you can position it.
If you don't want the user to see the div jump, give it the style visibility: hidden while you're positioning it:
CSS:
.hidden {
display: none;
visibility: hidden;
}
JS:
d3.select("#tooltip").style("display", "block");
// your div is still invisible, but now has a width.
// get its width and position it now
d3.select("#tooltip").classed("hidden", false); // now it will appear
If you hide it again, don't forget to reset the display
style as well!
Upvotes: 3