I have a chart with some circles on it. When the user hovers over a circle, I want to create a mouseover event and pass the x and y coordinates of the center of that circle. How do I do that?
svg.selectAll("circle")
.data(data)
.enter().append("circle")
.attr("cx", function(d) { return x(d.number); })
.attr("cy", function(d) { return y(d.area); })
.call(d3.my_helper.tooltip(function(d, i){return "Area: "+ d.area;}));
d3.my_helper.tooltip = function(accessor){
return function(selection){
var circle_x = ???; // the center of the circle
var circle_y = ???; // the center of the circle
selection.on("mouseover", function(d, i){
// do stuff here with circle_x and circle_y
});
};
};
You will need to find the offset of the svg elem itself and then add the "cy" attribute (center y) to the y coordinate and the "cx" attribute (center x) to the x coordinate accordingly:
If you are not using jQuery, consider using a usual hover event listener as well as
.offsetTop
and.offsetLeft
on the element.you might need to +/- some constant k_x, k_y to correct for static offsets as well as access to the scale factor if you are using the scale method on the graph, otherwise you can ignore these
*note you probably don't want to try and mix jQuery and D3 if you can use D3 since the event properties likely contain references to the data that can be used, for example, in rendering tooltips