How to use JavaScript getBoundingClientRect()? [SOLVED]


Written By - Olorunfemi Akinlua
Advertisement

Introduction to JavaScript getBoundingClientRect()

JavaScript's getBoundingClientRect() method is used to retrieve the size and position of an element on a web page, relative to the viewport. It is used to get the size and position of an element relative to the viewport (the visible part of the web page). It returns an object with several properties, including:

  • left: The distance of the left side of the element from the left side of the viewport.
  • top: The distance of the top of the element from the top of the viewport.
  • right: The distance of the right side of the element from the left side of the viewport.
  • bottom: The distance of the bottom of the element from the top of the viewport.
  • width: The width of the element in pixels.
  • height: The height of the element in pixels.
<div id="myDiv">
  <p>This is some text inside the div.</p>
</div>

<script>
  var myDiv = document.getElementById("myDiv");
  var rect = myDiv.getBoundingClientRect();
  console.log(rect.left);   // The distance of the left side of the div from the left side of the viewport
  console.log(rect.top);    // The distance of the top of the div from the top of the viewport
  console.log(rect.width);  // The width of the div in pixels
  console.log(rect.height); // The height of the div in pixels
</script>

In this example, we first get the div element by its id and then call the getBoundingClientRect() method on it, which returns the size and position of the div relative to the viewport. Then we log the values of the left, top, width, and height properties of the returned object to the console.

 

Simple Examples using getBoundingClientRect() method

Example 1: Getting the Width and Height of an Image

In this example, we use getBoundingClientRect() to get the width and height of an image. We first get the image element by its id, and then call the getBoundingClientRect() method on it. The returned object has the width and height of the image in pixels.

<img id="myImage" src="path/to/image.jpg" alt="My Image">

<script>
  var myImage = document.getElementById("myImage");
  var rect = myImage.getBoundingClientRect();
  console.log(rect.width);  // The width of the image in pixels
  console.log(rect.height); // The height of the image in pixels
</script>

 

Example 2: Getting the Position of an Element Relative to the Viewport

In this example, we use getBoundingClientRect() to get the position of a div relative to the viewport. We first get the div element by its id, and then call the getBoundingClientRect() method on it. The returned object has the left and top values of the div, which are the distance of the left and top of the div from the left and top of the viewport respectively.

<div id="myDiv">
  <p>This is some text inside the div.</p>
</div>

<script>
  var myDiv = document.getElementById("myDiv");
  var rect = myDiv.getBoundingClientRect();
  console.log(rect.left);   // The distance of the left side of the div from the left side of the viewport
  console.log(rect.top);    // The distance of the top of the div from the top of the viewport
</script>

 

Example 3: Determining if an Element is Visible in the Viewport

<div id="myDiv">
  <p>This is some text inside the div.</p>
</div>

<script>
  var myDiv = document.getElementById("myDiv");
  var rect = myDiv.getBoundingClientRect();
  var isVisible = (rect.top >= 0 && rect.left >= 0 && rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && rect.right <= (window.innerWidth || document.documentElement.clientWidth));
  console.log(isVisible);
</script>

In this example, we use getBoundingClientRect() to determine if a div is visible in the viewport. We first get the div element by its id, and then call the getBoundingClientRect() method on it. The returned object has the top, left, bottom, and right values of the div, which we use to check if the div is visible in the viewport. If all these values are greater than or equal to 0 and less than or equal to the viewport's width and height respectively, it means the element is visible in the viewport.

 

Complex Examples using getBoundingClientRect() method

The getBoundingClientRect() method can be called on any DOM element, such as a div, p, or img, and is often used in conjunction with other JavaScript methods and properties, such as scrollTop, offsetWidth, and clientHeight, to create dynamic and interactive web pages.

 

Example-1: For fixed element positioning

One common use case for getBoundingClientRect() is to create a fixed navigation bar that remains at the top of the page as the user scrolls. To do this, you would first create a reference to the navigation bar element using document.querySelector(), and then use getBoundingClientRect() to retrieve the position of the element relative to the viewport. You would then use an event listener to detect when the user scrolls, and use the scrollTop property to calculate the distance scrolled. Finally, you would use the style.top property to set the position of the navigation bar so that it remains at the top of the page.

<!DOCTYPE html>
<html>
    <head>
				<meta charset="UTF-8">
		    <meta http-equiv="X-UA-Compatible" content="IE=edge">
		    <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>javascript getboundingclientrect</title>
        <style>
            /* Add some styling to the navbar */
            .navbar {
                position: fixed;
                top: 0;
                left: 0;
                right: 0;
                background-color: rgb(155, 19, 19);
                color: #fff;
                padding: 10px;
            }
        </style>
    </head>
    <body>
        <nav class="navbar">
            <a href="#">Home</a>
            <a href="#">About</a>
            <a href="#">Contact</a>
        </nav>
        <div>
            <p>
                Lorem ipsum dolor sit amet, consectetur adipisicing elit.
                Doloremque corporis omnis sint cumque ut, laudantium facilis,
                voluptatum qui laborum ipsa consequatur, vitae nihil cupiditate
                ...
                inventore voluptates. Architecto nam cupiditate praesentium?
            </p>
        </div>
        <script>
            // Get the navigation bar element
            const navbar = document.querySelector(".navbar");

            // Get the position of the navbar relative to the viewport
            const navbarRect = navbar.getBoundingClientRect();

            // Add an event listener to detect when the user scrolls
            window.addEventListener("scroll", () => {
                // Calculate the distance scrolled
                const scrollTop =
                    window.pageYOffset || document.documentElement.scrollTop;

                // Set the position of the navbar so that it remains at the top of the page
                navbar.style.top = `${navbarRect.top + scrollTop}px`;
            });
        </script>
    </body>
</html>

Output

Advertisement

javascript getboundingclientrect in action

 

Example-2: For responsive design

Another use case for getBoundingClientRect() is to create a responsive design. You can use getBoundingClientRect() to retrieve the size and position of an element and then use the offsetWidth and clientHeight properties to calculate the dimensions of the viewport. Then you can use media queries to apply different CSS styles depending on the size of the viewport.

const element = document.querySelector(".my-element");
const rect = element.getBoundingClientRect();

const viewportWidth = rect.width;
const viewportHeight = rect.height;

if (viewportWidth > 800) {
    // Apply styles for larger screens
} else {
    // Apply styles for smaller screens
}

 

Example-3: Sticking a Header to the Top of the Viewport

In this example, we use getBoundingClientRect() to stick a header to the top of the viewport when the user scrolls down the page. We first get the header element by its id, and then call the getBoundingClientRect() method on it to get its initial position. Then we use the addEventListener() method to listen for the scroll event on the window. Inside the event listener function, we use getBoundingClientRect() again to get the current position of the header. If the top value of the header is less than 0, it means it has scrolled out of the viewport, so we set its top position to 0 to stick it to the top. If the top value is greater than or equal to 0, it means the header is still in the viewport, so we set its top position back to its initial position.

<header id="myHeader">
  <h1>My Website</h1>
  <nav>
    <a href="#">Home</a>
    <a href="#">About</a>
    <a href="#">Contact</a>
  </nav>
</header>

<div class="content">
  <p>Some content goes here...</p>
</div>

<style>
  #myHeader {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 1;
  }
</style>

<script>
  var myHeader = document.getElementById("myHeader");
  var rect = myHeader.getBoundingClientRect();
  var initialTop = rect.top;

  window.addEventListener("scroll", function() {
    var rect = myHeader.getBoundingClientRect();
    if (rect.top < 0) {
      myHeader.style.top = "0px";
    } else {
      myHeader.style.top = initialTop + "px";
    }
  });
</script>

 

Example-4: Lazy Load Images

In this example, we use getBoundingClientRect() to lazy load images on a webpage. We first select all the images with the class of "lazy" using querySelectorAll(), and store them in a variable called lazyImages. Then we create a function called checkInView() which will be used to check if the images are in the viewport. Inside the function, we use forEach() to loop through each image, and call getBoundingClientRect() on each one to get its position. We check if the top, left, bottom, and right values of the image are within the viewport, and if they are, we set the src attribute of the image to the value of its data-src attribute. This will cause the image to be loaded. Finally, we use the addEventListener() method to listen for the load, resize, and scroll events on the window, and call the checkInView() function whenever any of these events occur.

<img class="lazy" data-src="path/to/image1.jpg" alt="Image 1">
<img class="lazy" data-src="path/to/image2.jpg" alt="Image 2">
<img class="lazy" data-src="path/to/image3.jpg" alt="Image 3">

<script>
  var lazyImages = document.querySelectorAll(".lazy");

  function checkInView() {
    lazyImages.forEach(function(image) {
      var rect = image.getBoundingClientRect();
      if (rect.top >= 0 && rect.left >= 0 && rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && rect.right <= (window.innerWidth || document.documentElement.clientWidth)) {
        image.src = image.dataset.src;
      }
    });
  }

  window.addEventListener("load", checkInView);
  window.addEventListener("resize", checkInView);
  window.addEventListener("scroll", checkInView);
</script>

 

Summary

The getBoundingClientRect() method is a powerful JavaScript method that allows developers to retrieve the size and position of an element on a web page, relative to the viewport. It is often used in conjunction with other JavaScript methods and properties to create dynamic and interactive web pages, and it can be used to create responsive designs that adapt to different screen sizes.

 

Reference

Element.getBoundingClientRect() - Web APIs | MDN (mozilla.org)

 

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment