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.

Here's an example.

But first remember, getBoundingClientRect() will return values relative to the viewport.

<!DOCTYPE html>
<html>
<head>
  
<style>
  div, p { font-size: 18px; }
  
  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>
  
  <!-- display the coordinates of the above DIV -->
  <p id="coord"></p>
</body>

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

Also read... How to use .map() function to extract only numbers from an array of values?

← PreviousNext →

Happy coding. 🙂