Javascript DOM HTML Element getBoundingClientRect() Method

Introduction

Return the size of an element and its position relative to the viewport:

var rect = obj.getBoundingClientRect();

View in separate window

<!DOCTYPE html>
<html>
<head>

</head>/*from w  w w  .  j  av a 2s .  c  om*/

<body>

<p id="demo"></p>
<script>
function myFunction() {
  var div = document.getElementById("myDiv");
  var rect = div.getBoundingClientRect();
  x = rect.left;
  y = rect.top;
  w = rect.width;
  h = rect.height;
  document.getElementById("demo").innerHTML = "Left: " + x + ", Top: " + y + ", Width: " + w + ", Height: " + h;
}
</script>

<div style="height:200px; width:300px; overflow:auto;">
<div id="myDiv" style="width:250px; height:150px; border:1px solid red;">
this is a test. this is a test. this is a test. this is a test. this is a test. 
this is a test. this is a test. this is a test. this is a test. this is a test. 
this is a test. this is a test. this is a test. this is a test. this is a test. 
<br>
Use the scrollbars to test the method for different positions.
</div>
<div style="width:1000px; height:1000px;"></div>
</div>
<br>
<button onclick="myFunction()">Get top-left corner + witdth and height of the element with red border</button>
</body>
</html>

The getBoundingClientRect() method returns the size of an element and its position relative to the viewport.

This method returns a DOMRect object with eight properties:

  • left
  • top
  • right
  • bottom
  • x
  • y
  • width
  • height.

The top, left, bottom, and right change every time the scrolling position changes.

element.getBoundingClientRect();



PreviousNext

Related