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

← PrevNext →

You can use the getBoundingClientRect() method in JavaScript to find (or get) the position (x and y coordinates) of an HTML element.

getBoundingClientRect() Syntax

getBoundingClientRect()

The method takes no parametes. It returns the size of the element relative to the viewport.

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

← PreviousNext →