HTML | DOM getBoundingClientRect() Method

HTML DOM getBoundingClientRect() Method returns the relative positioning to the viewport.
It returns eight properties: left, top, right, bottom, x, y, width, height.
Scrolling will change the position value.

Syntax:

var rect = div.getBoundingClientRect();

Example:



filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
  
<head>
    <title>
        HTML | DOM getBoundingClientRect() Method
    </title>
    <script>
        function myFunction() {
            var div = document.getElementById("myDiv");
            var rectangle = div.getBoundingClientRect();
            x = rectangle.left;
            y = rectangle.top;
            w = rectangle.width;
            h = rectangle.height;
  
            alert("Left:" + x + ", Top:" + y +
                ", Width:" + w + ", Height:" + h);
        }
    </script>
</head>
  
<body>
    <button onclick="myFunction()">
        GET POSITION
    </button>
    <div style="height:300px; 
                width:400px;
                overflow:auto;">
  
        <div id="myDiv" style="width:350px;
                               height:250px; 
                               background-color:lightgreen;
                               border:2px SOLID green;">
  
            Use scrollbar to change the position.
        </div>
        <div style="width:1500px;
                    height:1500px; ">
        </div>
    </div>
    <br>
  
</body>
  
</html>

chevron_right


Output:
Before Click:

After Click:

Supported Browsers:

  • Chrome 1.0
  • Internet Explorer 9.0
  • FireFox 3.0
  • Opera 9.5
  • Safari 4.0


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.