DHTML Lab - DHTML Diner - Element Page Coordinates, Part 2 | 3 | WebReference

DHTML Lab - DHTML Diner - Element Page Coordinates, Part 2 | 3


Determining Element Page Coordinates, Part 2
IE for Windows and TABLEs

The Functions To-Now

At the end of Part 1, we had created two functions, reproduced below for your reference:

function DL_GetElementLeft(eElement)
{
    if (!eElement && this)                       // if argument is invalid
    {                                            // (not specified, is null or is 0)
        eElement = this;                         // and function is a method
    }                                            // identify the element as the method owner
    
    var nLeftPos = eElement.offsetLeft;          // initialize var to store calculations
    var eParElement = eElement.offsetParent;     // identify first offset parent element  
    while (eParElement != null)
    {                                            // move up through element hierarchy
        nLeftPos += eParElement.offsetLeft;      // appending left offset of each parent
        eParElement = eParElement.offsetParent;  // until no more offset parents exist
    }
    return nLeftPos;                             // return the number calculated
}
function DL_GetElementTop(eElement)
{
    if (!eElement && this)
    {
        eElement = this;
    }
    var nTopPos = eElement.offsetTop;
    var eParElement = eElement.offsetParent;
    while (eParElement != null)
    {
        nTopPos += eParElement.offsetTop;
        eParElement = eParElement.offsetParent;
    }
    return nTopPos;
}

These functions could be called in either of two ways:

elementReference.getTrueXPosition = DL_GetElementLeft;
elementReference.getTrueYPosition = DL_GetElementTop;
var nMyElementsTrueXPosition = elementReference.getTrueXPosition();
var nMyElementsTrueYPosition = elementReference.getTrueYPosition();

or:

var nMyElementsTrueXPosition = DL_GetElementLeft(elementReference);
var nMyElementsTrueYPosition = DL_GetElementTop(elementReference);

The functions are intended for use in IE for Windows and NS6+, and they are good enough for most applications or if one can live with a small margin of error.

As mentioned, the first problem one finds is when the element whose position we are trying to retrieve is nested in a TABLE.



Produced by Peter Belesis and

All Rights Reserved. Legal Notices.
Created: Oct 07, 2002
Revised: Oct 07, 2002

URL: http://www.webreference.com/dhtml/diner/realpos2/2.html