I want to display an overlay (html div) when a user clicks on an element in an SVG diagram. To visualize the problem I\'m having, suppose that the SVG image has a horizontal row
jQuery's position()
does not work well for SVG elements. There is a ticket for that.
You can use the native SVG method getBBox()
to get the position of a SVG element.
$('svg circle')[0].getBBox();
In case you haven't worked something out since March (and for anyone else having this problem), try getBoundingClientRect()
on your SVG node.
Returns a ClientRect
object that gives you top, bottom, left, right, width, and height relative to the document. Was able to use this to position Twitter Bootstrap popovers (divs) next to SVG rects.
You can get the position coordinate relative to the page of any element, also <svg>, with this little function:
function getOffset(element)
{
var bound = element.getBoundingClientRect();
var html = document.documentElement;
return {
top: bound.top + window.pageYOffset - html.clientTop,
left: bound.left + window.pageXOffset - html.clientLeft
};
}
var offset = getOffset(svg);
var x = offset.left;
var y = offset.top;
live demo: https://codepen.io/martinwantke/pen/rpNLWr