Tuesday, May 3, 2011

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.

From stackoverflow
  • 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.

    Peter Jacoby : Thanks, this is helpful, I'll look into the details of this.
  • 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

  • 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 

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

    Peter Jacoby : 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!

0 comments:

Post a Comment