472,122 Members | 1,548 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,122 software developers and data experts.

Distance between an element and the top of the page

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

Jul 20 '05 #1
1 9734


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/

Jul 20 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

20 posts views Thread by Xenophobe | last post: by
4 posts views Thread by Xenophobe | last post: by
14 posts views Thread by Wim Roffil | last post: by
10 posts views Thread by Alan Johnson | last post: by
11 posts views Thread by Dirntknow | last post: by
9 posts views Thread by nottheartistinquestion | last post: by
11 posts views Thread by devnew | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.