JavaScript: Get Absolute Element Position (Actual Position)

When your table with id = “myTbl” is located inside another table (TD), you will encounter that the offsetLeft of element myTbl is always return 0 (zero).
To get the actual position, use the following function:
What this function do is to append left offset of each parent exist in element hierarchy.
The same case also apply to offsetTop.

function GetActualElementLeft(eElement)
{
    if (!eElement && this)                      
    {                                           
        eElement = this;                        
    }                                            
   
    var nLeftPos = eElement.offsetLeft;         
    var eParElement = eElement.offsetParent;    
    while (eParElement != null)
    {                                           
        nLeftPos += eParElement.offsetLeft;     
        eParElement = eParElement.offsetParent; 
    }
    return nLeftPos;                            
}

function GetActualElementTop(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;
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s