Retrieves the left and top offset of an object using Javascript. I got this from Peter-Paul Koch's page http://www.quirksmode.org/js/findpos.html. His description is more extensive.
Code:function ObjectPosition(obj) {
var curleft = 0;
var curtop = 0;
if (obj.offsetParent) {
do {
curleft += obj.offsetLeft;
curtop += obj.offsetTop;
} while (obj = obj.offsetParent);
}
return [curleft,curtop];
}
Pass in the object you'd like the position of and it'll return a 2 item array. The first item is the left offset and the second item is the top offset.
Javascript only lets us check the offset from the object's parent. Since the object may be nested inside other elements, each of the parent's offsets must be added to get the final offset result.
The example below shows how to get the offset of an element called MyElementId. Place the code at the bottom of the BODY tag and right above </body>.
Code:<div id="MyElementId">My test element</div>
<script language="javascript" type="text/javascript">
var aryPosition = ObjectPosition(document.getElementById('MyElementId'));
document.write('MyElementId left offset is ' + aryPosition[0] + '<br />');
document.write('MyElementId top offset is ' + aryPosition[1] + '<br />');
</script>