D3's mouse coordinates relative to parent element

Patryk picture Patryk · Sep 2, 2013 · Viewed 14.6k times · Source

I would like to get mouse coordinates relative to parent or any other element in the DOM other than this but I keep getting

Uncaught TypeError: Object [object Array] has no method 'getBoundingClientRect' d3.v3.min.js:1
H d3.v3.min.js:1
vo.mouse d3.v3.min.js:3
(anonymous function) index.html:291
(anonymous function)

My code :

.on("mouseup", function(d){
    var th = d3.select( this );

    var coordinates = [0, 0];
    coordinates = d3.mouse( d3.select("body") );
    console.log( coordinates[1] );
    console.log( window );
    //th.attr("cy", d3.mouse),
    //d.newY = th.attr("cy");
    console.log(d);
});

As far as I have noticed I can only get mouse coordinates relative to element that I have attached .on("mouseup", ...) event listener.

Is there a way to get those coordinates relative to other element in the DOM ?

Answer

user879121 picture user879121 · Jun 2, 2015

d3.mouse expects a DOM element, not a d3 selection.

d3.mouse(d3.select('body').node())

Of course selecting the body can be even easier:

d3.mouse(document.body)

@Tom's answer works also in your case because you want the position relative to the page, but it doesn't work if you want the position relative to some other container.

Say you want to position a popup where the user clicked and you want to position it relative to the svg element so that it pans with the rest of your display.

nodeEnter.on('click', function(d){
  var coordinates = d3.mouse(svg.node());
});