I read many answers on this website and on other sites on clientLeft
and OffsetLeft
. but none give comprehensive explanation of what those values are.
Also, there are several sources on the web giving confusing or incorrect information.
Can someone could give me correct explanation of these terms with an visual example?
and how could I change these values, without using any CSS. I mean using only JavaScript .
The offsetLeft property returns the left position (in pixels) relative to the parent. The returned value includes: the left position, and margin of the element. the left padding, scrollbar and border of the parent.
The width of the left border of an element in pixels. It includes the width of the vertical scrollbar if the text direction of the element is right-to-left and if there is an overflow causing a left vertical scrollbar to be rendered. clientLeft does not include the left margin or the left padding.
The above answer explains it well, but here is a nice picture taken form this wonderful tutorial on coordinates.
offsetLeft
= position left
+margin
from the first positioned parent left
edge.clientLeft
= left border + left scrollbar width (if present). (block
level elements -only!)
Let's say we have a <div>
with 8px border and a scrollbar
var el = document.getElementById("test");
console.log( el.offsetLeft ); // (left + margin) 80 + 10 = 90
console.log( el.clientLeft ); // (border + left scrollbar) 8 + 0 = 8
#test {
overflow: auto;
position: absolute;
left: 80px; /* + */
margin-left: 10px; /* = 90px offsetLeft */
height: 100px;
width: 100px;
border: 8px solid red;
background: #f8f8f8;
}
<div id="test">
a<br>a<br>a<br>a<br>a<br>a<br>a<br>a
</div>
Using Right-To-Left text-direction direction: rtl;
the returned value will be: border + left scrollBar width (usually 17px).
8px border + 17px scrollbar* = ~25px
* (depends on browser default or custom styles)
var el = document.getElementById("test");
console.log( el.offsetLeft ); // (left + margin) 80 + 10 = 90
console.log( el.clientLeft ); // (border + left scrollbar*) 8 + ~17 = 25
#test {
overflow: auto;
position: absolute;
left: 80px; /* + */
margin-left: 10px; /* = 90px offsetLeft */
height: 100px;
width: 100px;
border: 8px solid red;
background: #f8f8f8;
direction: rtl; /* now text is `rtl` and scrollbar is at the left side! */
}
<div id="test">
a<br>a<br>a<br>a<br>a<br>a<br>a<br>a
</div>
Resources:
http://msdn.microsoft.com/en-us/library/ie/ms533564%28v=vs.85%29.aspx
https://developer.mozilla.org/en-US/docs/Web/API/Element.clientLeft
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement.offsetLeft
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