17
votes

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 .

2

2 Answers

20
votes

The above answer explains it well, but here is a nice picture taken form this wonderful tutorial on coordinates. offsetLeft vs clientLeft

20
votes

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