Peter Jacoby
Peter Jacoby

Reputation: 2416

Exact coordinate of html element within an iFrame

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.

Upvotes: 0

Views: 4411

Answers (3)

Tracker1
Tracker1

Reputation: 19344

well, I would suggest the jquery dimensions suggested if that works for you. For getting to the parent iframe, you will need to lookup against window.parent. You could then get your offset recursively through parents.

if (window.parent && window.parent.frames && window.parent.document && window.parent.document.getElementsByTagName) {
    var iframes = window.parent.document.getElementsByTagName("IFRAME");
    for (var i = 0; i < iframes.length; i++) {
        var id = iframes[i].id || iframes[i].name || i;
        if (window.parent.frames[id] == window) {
            //iframes[i] is your iframe in your parent.
        }
    }
}

I'm using this technique for identifying the frame in my FrameDialog plugin for jQueryUI.

Upvotes: 0

Lawrence Barsanti
Lawrence Barsanti

Reputation: 33342

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"></script>
// 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

Upvotes: 0

i_am_jorf
i_am_jorf

Reputation: 54640

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.

Upvotes: 1

Related Questions