Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get an object's absolute position on the page in Javascript? [duplicate]

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.

like image 552
Kip Avatar asked Sep 26 '09 00:09

Kip


People also ask

How do you find the absolute position of an element?

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.

How do you get the position of an element in a JavaScript?

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.

What is position absolute in JavaScript?

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.)


1 Answers

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)

like image 133
eyelidlessness Avatar answered Sep 23 '22 03:09

eyelidlessness