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.
http://www.quirksmode.org/js/findpos.html
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.
August 25th, 2010 at 8:14 pm
That’s a handy function right there! Saved me some time..
Cheers
Tulio
October 17th, 2011 at 6:08 pm
Works exactly what I want.
Thanks for post
October 18th, 2012 at 5:05 pm
Good Job. I like it!