[ACCEPTED]-Is it possible to get the position of div within the browser viewport? Not within the document. Within the window-css
You can do it in both - get the position 2 relative to the document, then subtract 1 the scroll position.
var e = document.getElementById('xxx');
var offset = {x:0,y:0};
while (e)
{
offset.x += e.offsetLeft;
offset.y += e.offsetTop;
e = e.offsetParent;
}
if (document.documentElement && (document.documentElement.scrollTop || document.documentElement.scrollLeft))
{
offset.x -= document.documentElement.scrollLeft;
offset.y -= document.documentElement.scrollTop;
}
else if (document.body && (document.body.scrollTop || document.body.scrollLeft))
{
offset.x -= document.body.scrollLeft;
offset.y -= document.body.scrollTop;
}
else if (window.pageXOffset || window.pageYOffset)
{
offset.x -= window.pageXOffset;
offset.y -= window.pageYOffset;
}
alert(offset.x + '\n' + offset.y);
[Pasting from the answer I gave here]
The native 5 getBoundingClientRect()
method has been around for quite a while 4 now, and does exactly what the question 3 asks for. Plus it is supported across all 2 browsers (including IE 5, it seems!)
From 1 this MDN page:
The returned value is a TextRectangle object, which contains read-only left, top, right and bottom properties describing the border-box, in pixels, with the top-left relative to the top-left of the viewport.
You use it like so:
var viewportOffset = el.getBoundingClientRect();
// these are relative to the viewport, i.e. the window
var top = viewportOffset.top;
var left = viewportOffset.left;
In IE and Firefox 3, you can use getBoundingClientRect for this; no 3 framework necessary.
But, yes, you should 2 use a framework if you need to support other 1 browsers as well.
You could subtract the div's offsetTop from 3 the document.body.scrollTop
This seems to 2 work on IE7 and FF3, but on a very simple 1 page. I haven't checked with nested DIVs.
Using Prototype it would be:
$('divname').viewportOffset.top
$('divname').viewportOffset.left
0
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.