Pages

Wednesday, June 9, 2010

Get Html Element Position in a web page

In order to find the position of an element on a webpage, Pass the element handle as parameter to the following function on the page. This function works with XPages on Notes Client as well.

function getElementPosition( htmlElement ) {
    var xPos = 0;
    var yPos = 0;
    
    while( htmlElement && !isNaN( htmlElement.offsetLeft ) && !isNaN( htmlElement.offsetTop ) ) {
        xPos += htmlElement.offsetLeft - htmlElement.scrollLeft;
        yPos += htmlElement.offsetTop - htmlElement.scrollTop;
        htmlElement = htmlElement.parentNode;
    }
    
    return { top: yPos, left: xPos };
}

Illustration,

Put the following code on a button which includes the above function and click it.

var myElement=document.getElementById(thisEvent.target.id);
try{
var coorde=getElementPosition( myElement );
var x = coorde.left;

var y = coorde.top;
alert(x+" "+y);
} catch (error) {
alert(error.message);
}

Hope that helps :)

No comments:

Post a Comment