brno792
brno792

Reputation: 6799

Get coordinates of mouse click on svg using d3

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?

Upvotes: 9

Views: 14292

Answers (2)

Daniel81
Daniel81

Reputation: 111

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.

Upvotes: 0

Stephen Thomas
Stephen Thomas

Reputation: 14063

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

Upvotes: 15

Related Questions