Is this doable in either IE7 or Firefox?
We can use the getBoundingClientRect method to get an element's position relative to its viewport. We get the div with querySelector . Then we call getBoundingClientRect on it to get an object with the top and left properties. top has the position relative to the top of the viewport.
The correct approach is to use element. getBoundingClientRect() to Get absolute position of element in JavaScript. Use element id to get its position in the browser window.
The vertical position of the element to be stuck can also be modified with the help of the 'top' property. It can be given a value of '0px' to make the element leave no space from the top of the viewport, or increased further to leave space from the top of the viewport.
Set the position of div at the bottom of its container can be done using bottom, and position property. Set position value to absolute and bottom value to zero to placed a div at the bottom of container.
You can do it in both - get the position relative to the document, then subtract 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 getBoundingClientRect()
method has been around for quite a while now, and does exactly what the question asks for. Plus it is supported across all browsers (including IE 5, it seems!)
From 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;
Try the dimensions jQuery plugin. See this demo.
$('#myelement.').offset();
In IE and Firefox 3, you can use getBoundingClientRect for this; no framework necessary.
But, yes, you should use a framework if you need to support other browsers as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With