sethbro
sethbro

Reputation: 1888

how to get d3.event.Y as location in a <g> element

In d3.js V4 the d3.event.y gives the event y location in a SVG element but I need the location of the event as it is in a G element. For example if a mouse is at the top of the G element than d3.event.y should be zero. But in my attempt it is only zero if the mouse is at the top of the SVG element. Here is my attempt: jsbin link - try dragging the 'water' line up and down. The water line never matches the mouse dragging. My SVG will scale with the width of the page so I cannot hard code values.

D3 V4 code:

var high = null;
d3.select('#bfG').call(
  d3.drag().on('start', function () {
    //get the real height of the <g> element
    high = this.getBoundingClientRect().height;
  }).on('drag', function () {
    // % of the location relative to the <g> height
    var p = (d3.event.y / high) * 100;
    var q = Math.max(0, Math.min(100, p));
    d3.select('#stop1').attr('offset', q + '%');
    d3.select('#stop2').attr('offset', q + '%');
  })
);

Upvotes: 0

Views: 1048

Answers (2)

1Cr18Ni9
1Cr18Ni9

Reputation: 1867

I must say your code is very intresting.

Well, I prepare to recommend you to use d3.mouse(container), then I think there is no difference between d3.mouse(container) and d3.event.y in this case, because you didn't transform the g element so the g element share the same coordinate system with svg.

I mean d3.mouse(this)[1] and d3.event.y will produce same value in this case.

Upvotes: 0

morganfree
morganfree

Reputation: 12472

You can use getBBox method to get y and height properties of the shape in the user space and then calculate offset:

var bbox = this.getBBox()
var p = (d3.event.y - bbox.y) / bbox.height * 100

examples: 1, 2

Upvotes: 1

Related Questions