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


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


<!DOCTYPE html>
  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; }

  <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. 🙂
  <p id="coord"></p>      <!-- show the coordinates of the above DIV -->

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

← PreviousNext →