0

Given an SVG created with d3, for example using

svg = d3.select("#someElement").append("svg")...

how do I find the top and left of the SVG in the absolute coordinates of the body, so that I can, for example, absolutely position a tooltip or other element relative to the top -left of the SVG with something like

tooltip.style("left", leftInBody + 72 + "px").style("top", topInBody + 20 + "px"); 
orome
  • 45,163
  • 57
  • 202
  • 418
  • the top left of your svg, unless scales set it otherwise, is simply 0,0 – tomtomtom Jun 19 '14 at 07:34
  • @tomtomtom: In the `body`? – orome Jun 19 '14 at 12:06
  • no, the coordinates in the svg area start from 0,0 in the top-left corner. otherwise you can use the methods posted here: http://stackoverflow.com/questions/442404/retrieve-the-position-x-y-of-an-html-element – tomtomtom Jun 19 '14 at 13:16

2 Answers2

1

You can do something like this (with jQuery):

var offset = $('#someElement svg').offset(),
    left = offset.left, top = offset.top;

also assuming that you're tooltip is a div outside of the root svg element.

If the tooltip is an svg element inside the root svg element, then you don't need to do this. The position you give it will automatically be relative to the root svg element.

victormejia
  • 1,174
  • 3
  • 12
  • 30
0

@victormejia answer is WRONG because is so old... We are in 2019 and D3 is so good!

Use d3.select(myElement).style('top'), d3.select(myElement).style('left').

Use parseInt() to clean the "px" string...
PS: to set a value, concatenate "px", d3.select(myElement).style('left',x+'px').

Peter Krauss
  • 13,174
  • 24
  • 167
  • 304