views:

695

answers:

3

How do I get the absolute x,y coordinates for an HTML element on a page that may exist within a iFrame. The page is sometimes called on its own and sometimes is called from within an iFrame.

This is the function that I wrote to figure out the x,y position based on the offsetLeft and offsetTop of the element and the offseParent.

function getXY(obj) 
{
var curObj = obj;
var curLeft = curTop = 0;

curLeft += curObj.offsetLeft
curTop += curObj.offsetTop;

while (curObj.offsetParent != null) 
{
 curObj = curObj.offsetParent;    
 curLeft += curObj.offsetLeft
 curTop += curObj.offsetTop;
}
obj.x = curLeft;
obj.y = curTop;
}

This works great if the page is the top, but the problem is that if the page is run from within an iFrame I do not know the offset of the iFrame on the page.

Is there a way to get the exact, absolutes coordinates regardless of whether the page is in an iFrame or not?

Thank you.

+1  A: 

I use JQuery Dimensions to do this. It does a good job of walking up the DOM and adding up all the offsets for you.

jeffamaphone
Thanks, this is helpful, I'll look into the details of this.
Peter Jacoby
A: 

Try using JavaScript framework like Dojo, or JQuery. They have all this basic functionality and work consistently across modern browsers.

In dojo:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/dojo/1.3/dojo/dojo.xd.js"&gt;&lt;/script&gt;
// box is an oject {l, t, w, h, x, y}
// (x,y) are the absolute coordinates
// (l,t) are the left and top offsets relative to the parent container
box = dojo.coords(aDomObj);

see http://docs.dojocampus.org/dojo/coords for more details

Lawrence Barsanti
A: 
Tracker1
Thanks, this is what I was looking for. I didn't think to get outside the current window, but using the window.parent and then getting a reference to the iframe is what I needed. Thanks!
Peter Jacoby