Languages

JavaScript - get the position of HTML element (X and Y coordinates)

0 points
Asked by:
Hayley-Mooney
677

How can I get the position of HTML element using JavaScript?

I need to find X and Y coordinates of elements such as images or divs.

1 answer
0 points
Answered by:
Hayley-Mooney
677

You can use getBoundingClientRect() to get the element's coordinates.

Quick solution:

var coords = element.getBoundingClientRect();

console.log(coords.top, coords.right, coords.bottom, coords.left);

 

Practical example

In this section, we present a practical example of how to get coordinates of an image that is inside a container div.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<head>
  <style>
    
    * {   /*  resets margins and paddings for all emelents  */
        margin: 0;
        padding: 0;
    }

    body {
        height: 300px;
    }
    
    img { /*  sets fixed size for all images                */
        width: 100px;
        height: 100px;
    }

    .container {
        position: absolute;
        left: 50px;
        top: 50px;
        border: 1px solid lightgray;
        height: 200px;
        width: 200px;
    }

  </style>
</head>
<body>
  <div class="container">
    <img id="image" src="https://dirask.com/static/bucket/1574890428058-BZOQxN2D3p--image.png" />
  </div>
  <script>

    var image = document.querySelector('#image');
    
    if (image) {
        var coordinates = image.getBoundingClientRect();

        console.log(coordinates.top);    // 1
        console.log(coordinates.right);  // 101
        console.log(coordinates.bottom); // 101
        console.log(coordinates.left);   // 1
    }

  </script>
</body>
</html>

Note:

We reset padding and margin before getting the coordinates, but there is 1px offsetfrom the image size because of the container border.

 

References

  1. Element.getBoundingClientRect() - Web APIs | MDN
0 comments Add comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join