I want to get an object's absolute x,y position on the page in Javascript. How can I do this?
I tried obj.offsetTop
and obj.offsetLeft
, but those only give the position relative to the parent element. I guess I could loop through and add the parent's offset, and its parent's offset, and so on until I get to the object with no parent, but it seems like there should be a better way. Googling didn't turn up much, and even SO site search isn't finding anything.
Also, I can't use jQuery.
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.
Use the Element. getBoundingClientRect() Function to Get the Position of an Element in JavaScript. The getBoundingClientRect() function produces a DOMRect object containing information about an element's size and position in the viewport.
An absolutely positioned element is an element whose computed position value is absolute or fixed . The top , right , bottom , and left properties specify offsets from the edges of the element's containing block. (The containing block is the ancestor relative to which the element is positioned.)
var cumulativeOffset = function(element) { var top = 0, left = 0; do { top += element.offsetTop || 0; left += element.offsetLeft || 0; element = element.offsetParent; } while(element); return { top: top, left: left }; };
(Method shamelessly stolen from PrototypeJS; code style, variable names and return value changed to protect the innocent)
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