dattebayo dattebayo - 4 months ago 11
Javascript Question

Finding the offset client position of an element

How to find the offset client position of an element using Javascript? (I assume the same code can be written in a BHO or Gecko/NPAPI).

The problem I am facing is a way to find out the offset client position of the element. The

e.srcElement.offsetX/Y
does not give the correct value always (same goes for clientX/Y). In some cases we also need to consider the parent element scroll.

How do we do this in general? Is there an easy way for this?

Answer
function getElementTop ( Elem ) 
{
    var elem;

    if ( document.getElementById ) 
    {   
        elem = document.getElementById ( Elem );
    } 
    else if ( document.all ) 
    {
        elem = document.all[Elem];
    }   		

    yPos = elem.offsetTop;
    tempEl = elem.offsetParent;

    while ( tempEl != null ) 
    {
        yPos += tempEl.offsetTop;
        tempEl = tempEl.offsetParent;
    }  

    return yPos;
}   


function getElementLeft ( Elem ) 
{
    var elem;

    if ( document.getElementById ) 
    {
        var elem = document.getElementById ( Elem );
    } 
    else if ( document.all )
    {
        var elem = document.all[Elem];
    }   		

    xPos = elem.offsetLeft;
    tempEl = elem.offsetParent; 		

    while ( tempEl != null ) 
    {
        xPos += tempEl.offsetLeft;
        tempEl = tempEl.offsetParent;
    }   		
    return xPos;
}

Pass the element id to the functions.

Comments