JS offsetTop property is not great and here is why

Alexandru Cambose
1 min readFeb 7, 2019

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 the offsetParent 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.

Working example

Tricky example

--

--

Alexandru Cambose

Full Stack Web Developer interested in Blockchain and AI. Currently available for freelance work. https://github.com/alexcambose https://alexcambose.com/