Entry
How do I get the absolute position of a non-positioned element ?
How do I get the absolute position of a non-positioned element ?
Oct 24th, 2003 08:09
Gavin Kistner, Thor Larholm, Dagon, Jumper, Phrogz
To get the absolute position of a non-positioned element (e.g., a SPAN
in a TD), you need to read the offsetLeft and offsetTop properties of
every element, including the element itself, that is an offsetParent to
the element.
function getDim(el){
for (var lx=0,ly=0;el!=null;
lx+=el.offsetLeft,ly+=el.offsetTop,el=el.offsetParent);
return {x:lx,y:ly}
}
Example usage:
<table><tr><td>
<span id=MySpan><img src="something" id=MyImage></span>
</td></tr></table>
<script>
mySpanDim = getDim(document.getElementById("MySpan"))
alert("x:" + mySpanDim.x + ", y:" + mySpanDim.y)
myImgDim = getDim(document.images.MyImage)
alert("x:" + myImgDim.x + ", y:" + myImgDim.y)
</script>
The above will work in IE4+ and NS6+/Mozilla. NS4 can only read the
absolute position of any image, by reading their x and y properties.
A version of the above that accounts for scrolled content can be found at:
http://phrogz.net/JS/FindXY_js.txt