Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
148
rated 0 times [  150] [ 2]  / answers: 1 / hits: 19001  / 10 Years ago, sat, november 29, 2014, 12:00:00

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 .


More From » html

 Answers
1

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>








The interesting part



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


[#68660] Wednesday, November 26, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jaycoborionc

Total Points: 220
Total Questions: 106
Total Answers: 120

Location: Kenya
Member since Mon, Jun 14, 2021
3 Years ago
;