It has probably happened to you at some point that you needed to implement new functionality that is based on getting the top position of an HTML element. After 10 seconds of searching on google (and probably ignoring the answers that contain jquery), here is the answer: element.offsetTop()
. Everything is great, you copy-paste the function in your code and done, it returns the top position. You are lucky.
Well, now I’m gonna show you some little details of this property that you probably didn’t take into consideration.
Upon further investigation, from the MDN docs:
The
HTMLElement.offsetTop
read-only property returns the distance of the current element relative to the top of theoffsetParent
node.
So it seems that the offsetTop
property does not actually take the “absolute” position but relative to its parent element that has a relative position.