[ACCEPTED]-Is it possible to get the position of div within the browser viewport? Not within the document. Within the window-css

Accepted answer
Score: 36

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);
Score: 12

[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;
Score: 4

Try the dimensions jQuery plugin. See this demo.

$('#myelement.').offset();

0

Score: 3

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.

Score: 0

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.

Score: 0

Using Prototype it would be:

$('divname').viewportOffset.top
$('divname').viewportOffset.left

0

More Related questions