Tuesday, December 20, 2011

JavaScript Find Absolute Position of element

Scenario: Get coordinates of a element (X, Y) to display overlay message immediate next or immediate below the element.
Based on the coordinates set the absolute position of the control (overlay) to display it accordingly. The overlay can be started any side/corner of the element.

Get the element object using JavaScript:
var obj = document.getElementById("controlelement");
Get the position of the element from Left
function findPosLeft(obj) 
{
    var posLeft = 0;
    if (obj.offsetParent) 
    {
        while (obj.offsetParent) 
        {
            posLeft += obj.offsetLeft;
            obj = obj.offsetParent;
        }
    }
    else if (obj.x) 
    {
        posLeft += obj.x;
    }

    return posLeft;
}
Get the position of the element from Top
function findPosTop(obj) 
{
    var posTop = 0;
    if (obj.offsetParent) 
    {
        while (obj.offsetParent) 
        {
            posTop += obj.offsetTop;
            obj = obj.offsetParent;
        }
    }
    else if (obj.y) 
    {
        posTop += obj.y;
    }
    return posTop;
}
Get the position of the element from Bottom
function findPosBottom(obj) 
{
    var posBottom = 0;
    if (obj.offsetParent) 
    {
        posBottom += obj.offsetHeight;
        while (obj.offsetParent) 
        {
            posBottom += obj.offsetTop;
            obj = obj.offsetParent;
        }
    }
    else if (obj.y) 
    {
        posBottom += obj.y;
        posBottom += obj.height;
    }
    return posBottom;
}
Get the position of the element from Right
function findPosRight(obj) 
{
    var posRight = 0;
    if (obj.offsetParent) 
    {
        posRight += obj.offsetWidth;
        while (obj.offsetParent) 
        {
            posRight += obj.offsetLeft;
            obj = obj.offsetParent;
        }
    }
    else if (obj.x) 
    {
        posRight += obj.x;
        posRight += obj.width;
    }
    return posRight;
}

No comments:

Post a Comment