Distance between an element and the top of the page

G

Gilles Lenfant

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.

Many thanks in advance.

--Gilles
 
M

Martin Honnen

Gilles said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,767
Messages
2,569,570
Members
45,045
Latest member
DRCM

Latest Threads

Top