Tuesday, May 05, 2009

Getting a HTML elements absolute position

There might be a case where we may want a popup to be displayed near the anchor element that we click, in that case the popup's postion is difficult to set , here is the code how we get the position of the anchor tag so that we can set the popup's position near to it,


function getoffsetLeft(element)
{
if(!element) return 0;
return element.offsetLeft + getoffsetLeft(element.offsetParent);
}
function getoffsetTop(aItem2)
{
if(!aItem2) return 0;
return aItem2.offsetTop + getoffsetTop(aItem2.offsetParent);
}

var leftp=getoffsetLeft(document.getElementById('anchor'))+10;
var topp=getoffsetTop(document.getElementById('anchor'))-10;

alert(leftp);alert(topp);



In the above code 'element' is the anchor tag object ie.(document.getElementById('anchor')). The alert would display the required top,left values for the popup.The speciality of this code is that it would get the top,left values even if the anchor tags position is relative.

No comments:

Computers Add to Technorati Favorites Programming Blogs - BlogCatalog Blog Directory