Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
97
rated 0 times [  104] [ 7]  / answers: 1 / hits: 21356  / 11 Years ago, wed, july 31, 2013, 12:00:00

I have a following DOM structure



<body>
<div>
<table>
<outerElement>
<innerElement />
</outerElement>
<table>
</div>
</body>


DIV has its overflow set to auto so if table grows bigger - it scrolls within the DIV.



In this scenario why table.offsetParent returns the body while both table.parentNode and parentElement return the Div?



I need to calculate current position of the innerElement within the window, so I traverse from it up thru all parent elements, collecting their offsetTop and offsetLeft values. Up until the DIV offsetParent works fine and then it skips it directly to the body. The problem if there's scrolling involved at some point, I need to account for scrollTop and scrollLeft as well - like in the DIV in the above example. The problem is if I use offsetParent I never encounter the DIV as one of the parents.



UPDATE



This is part of the code that does the traversing:



while (oElem && getStyle(oElem, 'position') != 'absolute' && getStyle(oElem, 'position') != 'relative') { 
curleft += oElem.offsetLeft;
curtop += oElem.offsetTop;
oElem = oElem.offsetParent;
}


where getStyle is a custom function that in this case retrieves the position style.


More From » html

 Answers
20

Stay clear of offsetParent, you'll have to add lots of hacks and checks to ensure you get it right.



Try using getBoundingClientRect instead.


[#76623] Tuesday, July 30, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
nathanaelzechariahl

Total Points: 745
Total Questions: 86
Total Answers: 103

Location: Finland
Member since Fri, Oct 21, 2022
2 Years ago
;