Retrieve the position (X, Y) of an Element using HTML

Retrieve the position (X, Y) of an Element using HTML

Answer: You can use the getBoundingClientRect() function to retrieve the position(X, Y) of an HTML element.

The position(X, Y) refers to the coordinates of an element on the webpage. The X coordinate tells how far the element is from the left edge of the page, and the Y coordinate tells how far it is from the top edge.  There are a few methods, such as getBoundingClientRect() and offsetLeft and offsetTop, to retrieve the position of HTML elements.  We will discuss these methods in this blog in detail.

Table of Contents:

Why Retrieve the position(X, Y) of an HTML Element?

When you are working on web development, you need to know the position of the HTML elements. That would be helpful for creating custom tooltips, managing drag-and-drop features, or doing animations based on where elements are. JavaScript makes it easy by retrieving the position of elements to the viewport.

Understanding the Position Context

  • X coordinate: How far the target element is from the left edge of the page (or parent element).
  • Y coordinate: How far the target element is from the top edge of the page (or parent element).

These values are usually in pixels, but you can use other units depending on your needs.

Methods to Retrieve the position(X, Y) of an HTML element

JavaScript functions like getBoundingClientRect() and offsetLeft and offsetTop are used to retrieve the position of an HTML element.  Let’s discuss these methods in detail.

Method 1: Using getBoundingClientRect() 

You can use the getBoundingClientRect() method to get the position. This method gives you a DOMRect object with details about where the element is on the screen compared to the viewport.

Example:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Get Position using getBoundingClientRect()</title>
    <style>
        #myElement {
            width: 200px;
            height: 100px;
            background-color: lightblue;
            margin-top: 50px;
            margin-left: 100px;
        }
    </style>
</head>
<body>
    <div id="myElement">Click me to get my position</div>
    <script>
        document.getElementById("myElement").addEventListener("click", function() {
            let rect = this.getBoundingClientRect();
            alert("X: " + rect.left + ", Y: " + rect.top);
        });
    </script>
</body>
</html>

Output:

Using getBoundingClientRect()

Explanation: When you click on the element, it shows an alert with the X (horizontal) and Y (vertical) positions of the element relative to the viewport.

Method 2: Using offsetLeft and offsetTop

You can use the offsetLeft and offsetTop functions to get the position of an HTML element. You will get the distance of the element relative to the offset parent, which is present near the positioned ancestor.

Example:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Get Position using offsetLeft and offsetTop</title>
    <style>
        #parent {
            position: relative;
            width: 300px;
            height: 200px;
            background-color: lightgray;
        }
        #myElement {
            width: 150px;
            height: 100px;
            background-color: lightgreen;
            position: absolute;
            top: 50px; /* Adjusted top position */
            left: 75px; /* Adjusted left position */
        }
    </style>
</head>
<body>

    <div id="parent">
        <div id="myElement">Click me to get my position</div>
    </div>
    
    <script>
        document.getElementById("myElement").addEventListener("click", function() {
            let x = this.offsetLeft;
            let y = this.offsetTop;
            alert("X: " + x + ", Y: " + y);
        });
    </script>

</body>
</html>

Output:

Using offsetLeft and offsetTop Output

Explanation: You can get the position of the X and Y when you click the event. You can see that the #myElement div is positioned relative to its parent.

Best Practices

You can use the getBoundingClientRect() if you want the exact position and the element location relative to the viewport. You can use offsetLeft and offsetTop if you want the element’s position relative to its parent. And be careful with using offsetLeft and offsetTop as they don’t consider page scrolling.

Conclusion

You can use the JavaScript function to retrieve the position of HTML elements. Using functions such as getBoundingClientRect() and offsetLeft and offsetTop, you can get the position of an element. For the modern and dynamic webpage, getBoundingClientRect() would be the great choice due to its accuracy.

Retrieve the position (X, Y) of an HTML Element – FAQs

1. How can I retrieve the position (X, Y) of an HTML element?

You can use the getBoundingClientRect() method to get the position of an element relative to the viewport.

2. What is the getBoundingClientRect() method?

This method returns a DOMRect object containing information about the element’s position and size relative to the viewport.

3. How do I use getBoundingClientRect() to get an element's position?

Call the getBoundingClientRect() method on the element, and use the top and left properties of the resulting DOMRect object for the Y and X coordinates.

4. When should I use offsetLeft and offsetTop?

Use these properties when you need the position relative to the parent element and scrolling doesn’t affect your layout.

5. What's the difference between getBoundingClientRect() and offsetLeft/offsetTop?

getBoundingClientRect() provides the position relative to the viewport, while offsetLeft and offsetTop give the position relative to the parent element and don’t account for page scrolling.

About the Author

Technical Research Analyst - Full Stack Development

Kislay is a Technical Research Analyst and Full Stack Developer with expertise in crafting Mobile applications from inception to deployment. Proficient in Android development, IOS development, HTML, CSS, JavaScript, React, Angular, MySQL, and MongoDB, he’s committed to enhancing user experiences through intuitive websites and advanced mobile applications.

Full Stack Developer Course Banner