I want to get the position of an element relative to the browser window (the viewport in which the page is diaplayed, not the whole page), how can this be done in javascript?
Many thanks
I want to get the position of an element relative to the browser window (the viewport in which the page is diaplayed, not the whole page), how can this be done in javascript?
Many thanks
Edit: Add some code to account for the page scrolling.
function findPos(id) {
var node = document.getElementById(id);
var curtop = 0;
var curtopscroll = 0;
if (node.offsetParent) {
do {
curtop += node.offsetTop;
curtopscroll += node.offsetParent ? node.offsetParent.scrollTop : 0;
} while (node = node.offsetParent);
alert(curtop - curtopscroll);
}
}
The id argument is the id of the element whose offset you want. Adapted from a quirksmode post.
The function on this page will return a rectangle with the top, left, height and width co ordinates of a passed element relative to the browser view port.
localToGlobal: function( _el ) {
var target = _el,
target_width = target.offsetWidth,
target_height = target.offsetHeight,
target_left = target.offsetLeft,
target_top = target.offsetTop,
gleft = 0,
gtop = 0,
rect = {};
var moonwalk = function( _parent ) {
if (!!_parent) {
gleft += _parent.offsetLeft;
gtop += _parent.offsetTop;
moonwalk( _parent.offsetParent );
} else {
return rect = {
top: target.offsetTop + gtop,
left: target.offsetLeft + gleft,
bottom: (target.offsetTop + gtop) + target_height,
right: (target.offsetLeft + gleft) + target_width
};
}
};
moonwalk( target.offsetParent );
return rect;
}
You can try:
node.offsetTop - window.scrollY
It works on Opera with viewport meta tag defined.
Just grab a copy of prototype at http://prototypejs.org/download. I believe you can get what you're looking for instantly with:
http://prototypejs.org/api/element/viewportoffset
Otherwise, go for:
http://prototypejs.org/api/document/viewport/getscrolloffsets
http://prototypejs.org/api/element/cumulativeoffset
(considering you know how to get the element's offset relative to the page, you will understand this)
EDIT By using libraries like prototype you will have the big advantage of easily coding crossbrowser compatible code. If for some reason you don't like prototype, I can recommend either jquery, or dojo
Thanks for all the answers. It seems Prototype already has a function that does this (the page() function). By viewing the source code of the function, I found that it first calculates the element offset position relative to the page (i.e. the document top), then subtracts the scrollTop from that. See the source code of prototype for more details.