Find the (x, y) position of an HTML element using JavaScript

← PrevNext →

In JavaScript, the getBoundingClientRect() method provides a simple and reliable way to determine the exact position of an HTML element on the screen. It returns a DOMRect object containing the element's size and its coordinates, specifically the x and y values, relative to the viewport. This method is especially useful for building dynamic interfaces, aligning elements precisely, or triggering animations based on scroll position.

Syntax (getBoundingClientRect())

getBoundingClientRect()

The method takes no parameters. It returns the size of the element relative to the viewport. The getBoundingClientRect() method is called directly on a DOM element and returns a DOMRect object containing properties like top, left, right, bottom, width, and height.

Example:

<!DOCTYPE html>
<html>
<head>
<style>
  body { height: 2000px; width: 1000px; }
  
  #theText { 
    width: 300px; 
    padding: 10px; 
    border: solid 1px #ddd;
    position: absolute;
    bottom: 2%;
    left: 30%;
  }
  
  p { position: fixed; } 
  #coord { top: 50px; }
</style>
</head>

<body>
  <h2>Scroll this page up and down</h2>

  <div id='theText'>
    Hi, I am a DIV element. Scroll this page up and down to get my position or the X and Y coordinates. 🙂
  </div>
  <p id="coord"></p>      <!-- Show the coordinates of the above DIV -->
</body>

<script>
    window.addEventListener('scroll', function (e) {
        document.getElementById('coord').innerHTML =
            'X: ' + theText.getBoundingClientRect().left +
            ' Y: ' + theText.getBoundingClientRect().top;
    });
</script>
</html>
Try it

Why Use getBoundingClientRect()

1. Viewport relative positioning: It is perfect for tasks like aligning tooltips, popups, or floating elements near a target element, especially when the page is scrollable.
2. Responsive design: Helps dynamically adjust layout or animations based on where elements appear on screen.
3. Scroll aware interactions: Since the values update as the user scrolls, it's ideal for sticky headers, lazy loading, or triggering animations when elements enter the viewport.

When You Should Use getBoundingClientRect()

1. You need precise screen position regardless of scroll offset.
2. You're working with fixed position elements or overlays.
3. You want to detect visibility or intersection with the viewport (e.g., for scroll triggered effects).

← PreviousNext →