Gilles Lenfant wrote:
Hi,
I got an element ( say <div id="foo">... ) at its natural position in a
page.
I need to get the distance (in pixels) between the top of that element and
the top of the page/frame.
Of course, I'd prefer this to work with IE and Mozilla family.
With Netscape 6+, IE4+ and (at least) Opera 6+ any element object has
properties
offsetLeft
offsetTop
offsetParent
where the first two give you the coordinates relative to the last, the
offsetParent. If you add offsetLeft/offsetTop along the offsetParent
hierarchy you get the page coordinates of the element:
function getPageCoords (element) {
var coords = { x: 0, y: 0};
while (element) {
coords.x += element.offsetLeft;
coords.y += element.offsetTop;
element = element.offsetParent;
}
return coords;
}
function getElementObject (elementId) {
if (document.all)
return document.all[elementId];
else if (document.getElementById)
return document.getElementById(elementId);
else
return null;
}
var coords = getPageCoords(getElementObject('elementId'));
alert(coords.x + ':' + coords.y)
Make sure you call getPageCoords after the page has been loaded
--
Martin Honnen
http://JavaScript.FAQTs.com/