In this section, we will learn what the Element offsetLeft property is and how to use it in JavaScript.
What is Element offsetLeft Property in JavaScript?
The JavaScript Element offsetLeft property is used to get the distance in pixels between the outer left border of the current element (the one that invoked the property) and the inner left border of the offsetParent node.
Note: please check the offsetParent property if you’re not familiar with it.
JavaScript offsetLeft Property Syntax:
element.offsetLeft;
JavaScript offsetLeft Property Input Value
The offsetLeft property is read-only and so we can’t assign a value to it.
Example: using offsetLeft Property in JavaScript
See the Pen using offsetLeft Property in JavaScript by Omid Dehghan (@odchan1) on CodePen.
How does Element offsetLeft property work in JavaScript?
The distance between the left inner border of the offsetParent node (the <ol> element in this example) and the outer left border includes the left padding of the offsetParent node and the left margin of the current element.
So if we combine these two values, we should get the 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.