My question is fairly straightforward: How can you find the offsetTop
of a child element compared to it's parent element (rather than the window top)?
The definition of offsetTop
states that the property will return the value by which a child element is offset from the top of an offsetParent
, but this doesn't seem to be the case in this JSFiddle: http://jsfiddle.net/h5KBK/.
My goal is to find the offset of the bolded orange text from the top of the scrollable div, not the window top. Is there any way to do this without calculating the heights of the above elements, paddings, margins, etc. and subtracting it from the offsetTop
?
I'm looking for a JavaScript only solution. No jQuery please.
We can also use the jQuery position() method. The position() method is an inbuilt method in jQuery which is used to find the position of the first matched element relative to its parent element in the DOM tree.
We can use the getBoundingClientRect method to get an element's position relative to its viewport. We get the div with querySelector . Then we call getBoundingClientRect on it to get an object with the top and left properties. top has the position relative to the top of the viewport.
offsetTop read-only property returns the distance of the outer border of the current element relative to the inner border of the top of the offsetParent , the closest positioned ancestor element.
The offsetTop property returns the top position (in pixels) relative to the parent. The returned value includes: the top position, and margin of the element. the top padding, scrollbar and border of the parent.
By definition offsetTop
returns the top position of the object relative to the top side of its offsetParent
element, in pixels.
Now offsetParent
needs to be an element with a position other than static. If you change the position attribute of scroll
element in your fiddle I get a value of 1012 as opposed to 1110 without the position attribute.
Actually, I did some more research and figured out the answer. The offsetParent
must have a specified position:absolute
or position:relative
declaration, as shown in this JSFiddle: http://jsfiddle.net/h5KBK/1/
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