9

I want to get the coordinates of a mouse click on a rectangular shaped svg. I'm trying to print the mouse click coordinates to the console.

I can use pageX and pageY to get the coordinates, but that is of the entire page. I just need the coordinates inside the svg.

I'm using d3.v3.min.js

So I tried:

$(document).mousedown(function () {
     console.log(d3.mouse(this));
});

I get the error:

Uncaught TypeError: Cannot read property 'sourceEvent' of null

I also tried:

$(document).mousedown(function () {
     console.log(d3.mouse(document.getElementById("svg_id")));
});

I get the same error.

When I try with d3.svg.mouse(this), I get error:

Uncaught TypeError: undefined is not a function

How can I get the click coordinates in the svg and why are these d3.mouse() functions not working?

Cleb
  • 25,102
  • 20
  • 116
  • 151
brno792
  • 6,479
  • 17
  • 54
  • 71
  • Wondering if this may help.. http://stackoverflow.com/questions/16770763/mouse-position-in-d3 – Ian Dec 11 '14 at 20:17
  • thanks, but trying those examples I am still getting the sourceEvent null error. – brno792 Dec 11 '14 at 20:39
  • I don't know d3 well, but a quick look at the docs suggest that the parameter should be a container (like an svg or g element). I have no idea what 'shape' is, but you may want to check that. Otherwise maybe post up a fiddle. – Ian Dec 11 '14 at 20:51
  • can you post the code of the svg element creation. The rectangular shape you mention. – gaitat Dec 11 '14 at 22:05

2 Answers2

15

The problem with your code is that you're using jQuery event handling instead of D3 event handling. You want something like the following:

var svg = d3.select("svg");
svg.on("click", function() {
    console.log(d3.mouse(svg.node));
})
Stephen Thomas
  • 13,843
  • 2
  • 32
  • 53
  • 6
    To clarify: the values used by `d3.mouse` are set by d3 when it intercepts an event and passes it to your event handler; so, you can only use `d3.event(containerElement)` in an event handler registered with the d3 `.on()` method. – AmeliaBR Dec 12 '14 at 00:05
  • 3
    After a lot of mucking around, I found that just `d3.mouse(this)` worked inside the `svg.on('click')` function. – Michael Scheper Oct 27 '16 at 21:02
  • ``` var coords = d3.pointer( event );``` – Fida Jan 22 '22 at 17:33
0

Maybe time for an update here? Using JSv7, I think this would be the equivalent snippet:

svg.on("click", d => console.log([d.clientX, d.clientY]));

Lately it seems d3JS has gone to directly using the ClientX and ClientY properties of the node in which the event occurred without any sort of "mouse" object/methods.

Daniel81
  • 81
  • 4