Sunday, April 3, 2011

How can I determine the absolute position of an element within an iframe taking in to account the frame's scroll in javascript?

I'd like to know the absolute position (pixels from top and left) of a HTML element within an iFrame that has scrolled. I've tried using the 'findpos' script from quirksmode (http://www.quirksmode.org/js/findpos.html):

function findPos(obj) {
    var curleft = curtop = 0;
    if (obj.offsetParent) {
        do {
            curleft += obj.offsetLeft;
            curtop += obj.offsetTop;
        }
        while (obj = obj.offsetParent);
        return [curleft, curtop];
    }
}

This doesn't seem to account for the fact that the iFrame may have scrolled. How can I modify this script to account for the scroll of the iFrame?

From stackoverflow
  • function findPosRelativeToViewport(obj) {
        var pos= findPos(obj);
        var root= document.compatMode=='BackCompat'? document.body : document.documentElement;
        pos[0]-= root.scrollLeft;
        pos[1]-= root.scrollTop;
        return pos;
    }
    

    (the compatMode stuff being to cater for IE in Quirks Mode. But don't use Quirks Mode.)

0 comments:

Post a Comment