JavaScript offsetTop Property Tutorial

In this section, we will learn what the Element offsetTop property is and how to use it in JavaScript.

What is Element offsetTop Property in JavaScript?

The JavaScript Element offsetTop property is used to get the distance in pixels between the outer top border of the current element (the one that invoked the property) and the inner top border of the offsetParent node.

JavaScript offsetTop property
JavaScript offsetTop property

Note: please check the offsetParent property if you’re not familiar with it.

JavaScript offsetTop Property Syntax:

element.offsetTop;

JavaScript offsetTop Property Input Value

The offsetTop property is read-only and so we can’t assign a value to it.

Example: using offsetTop Property in JavaScript

See the Pen using offsetTop Property in JavaScript by Omid Dehghan (@odchan1) on CodePen.

How does Element offsetTop property work in JavaScript?

The distance between the top inner border of the offsetParent node (the <ol> element in this example) and the outer top border includes the top padding of the offsetParent node and the top margin of the current element.

So if we combine these two values, we should get the result distance for this particular example:

21px + 21px = 42px;

But remember, in other scenarios, there might be other nodes between these two elements which will affect the final distance.

Leave a Reply