Javascript DOM HTML Element offsetWidth Property with scrollbar

Introduction

This example demonstrates the difference between clientHeight/clientWidth and offsetHeight/offsetWidth, when we add a scrollbar to the element:

Click the button to get the clientHeight, offsetHeight, clientWidth and offsetWidth of div.

View in separate window

<!DOCTYPE html>
<html>
<head>
<style>
#myDIV {/*ww  w  . ja v a  2  s .  com*/
  height: 250px;
  width: 400px;
  padding: 10px;
  margin: 15px;
  border: 5px solid red;
  background-color: lightblue;
  overflow: auto;
}

#myDIV2 {
  height: 250px;
  width: 400px;
  padding: 10px;
  margin: 15px;
  border: 5px solid red;
  background-color: lightblue;
}

#content {
  height: 800px;
  width: 2000px;
  background-color: lightyellow;
}
</style>
</head>
<body>
<button onclick="myFunction()">Test</button>


<div id="myDIV">
  <div id="content"></div>
</div>

<div id="myDIV2">
  <div id="content2"></div>
</div>

<script>
function myFunction() {
  var elmnt = document.getElementById("myDIV");
  var txt = "";
  txt += "<b>Information about div1:</b><br>";
  txt += "Height including padding: " + elmnt.clientHeight + "px<br>";
  txt += "Height including padding, border and scrollbar: " + elmnt.offsetHeight + "px<br>";
  txt += "Width including padding: " + elmnt.clientWidth + "px<br>";
  txt += "Width including padding, border and scrollbar: " + elmnt.offsetWidth + "px";
  document.getElementById("content").innerHTML = txt;

  var elmnt2 = document.getElementById("myDIV2");
  var txt2 = "";
  txt2 += "<b>Information about div2:</b><br>";
  txt2 += "Height including padding: " + elmnt2.clientHeight + "px<br>";
  txt2 += "Height including padding and border: " + elmnt2.offsetHeight + "px<br>";
  txt2 += "Width including padding: " + elmnt2.clientWidth + "px<br>";
  txt2 += "Width including padding and border: " + elmnt2.offsetWidth + "px";
  document.getElementById("content2").innerHTML = txt2;
}
</script>

</body>
</html>



PreviousNext

Related