find absolute position of an html element

JavaScript Add comments

Html elements are displayed cascading by default. So every element appears one after the other and it is the same with nested elements. I mean elements within another element.

I want to find the exact absolute position of an element. In other words i want to find the exact x,y of an element in the html page if you could consider the html page as a graph.

I used left and top but it will always give the x and y with respect to the parent and not to the window or the body tag which is the first parent for all visible elements. Then i read about the property offsetLeft and offsetTop but this too is with respect to the parent.

So find the parents left + its parent left + its parent till you reach the top then you will get the left of any element. The same way for finding the top that is y. here is the function which will give you the x,y/absolute position of any element.

But when i used float left property i found this function returned a different value so please check when using float left option. anyway …

function findAbsolutePosition(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		} while (obj = obj.offsetParent);
	return [curleft,curtop];
//returns an array

and to my surprise i found the following link when i tried to find something like this to check my work.

I use this site to cross check my snippets in javascript if present. This is one useful site i have found which analyses beyond the scope.

3 Responses to “find absolute position of an html element”

  1. Tulio Domingos Says:

    That’s a handy function right there! Saved me some time..



  2. Hummer Says:

    Works exactly what I want.
    Thanks for post

  3. Nels Says:

    Good Job. I like it!

Leave a Reply

Entries RSS