user_78361084
user_78361084

Reputation: 3908

How do I get the x,y coordinates of the center of the circle the user mouses over?

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
                });
            };
        }; 

Upvotes: 1

Views: 7650

Answers (2)

D.Deriso
D.Deriso

Reputation: 4397

.on('mouseover', function(d) {
    var target_x = d3.event.target.cx.animVal.value*scale + k_x;
    var target_y = d3.event.target.cx.animVal.value*scale + k_y;
}

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

Upvotes: 3

Vinay
Vinay

Reputation: 6322

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:

$('circle').hover(function (ev) {
    var svgPos = $('svg').offset(),
        x = svgPos.left + $(ev.target).attr('cx'),
        y = svgPos.top + $(ev.target).attr('cy'),
        coords = [x, y];

    // coords now has your coordinates
});

If you are not using jQuery, consider using a usual hover event listener as well as .offsetTop and .offsetLeft on the element.

Upvotes: 2

Related Questions