422,351 Members | 1,431 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 422,351 IT Pros & Developers. It's quick & easy.

Distance between an element and the top of the page

P: n/a
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
Share this Question
Share on Google+
1 Reply


P: n/a


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.