Button Position Retrieval on Webpage

To obtain the position of buttons on a web page, we can use the getBoundingClientRect() method. This method provides us with information about an element’s size and position in the viewport. By using this method, we can obtain the X and Y coordinates of a button when it is clicked.

Example 1: This example shows how to get the position of an element by clicking on the button in an HTML document

html




<!DOCTYPE html>
<html>
 
<head>
    <title>
        Retrieve the position (X,Y) of an element
    </title>
 
    <!-- JavaScript code to display position -->
    <script type="text/javascript">
 
        function getPositionXY(element) {
            let rect = element.getBoundingClientRect();
            document.getElementById('gfg').innerHTML =
                'X: ' + rect.x + ', ' + 'Y: ' + rect.y
        }
    </script>
</head>
 
<body>
    <h2>Retrieve the position (X,Y) of an element using HTML</h2>
 
    <!-- Click on button to get its co-ordinate -->
    <button id='button1'
            onclick="getPositionXY(this)">
        Button 1
    </button>
 
    <button id='button1'
            onclick="getPositionXY(this)">
        Button 2
    </button>
 
    <br><br>
    <button id='button1'
            onclick="getPositionXY(this)">
        Button 3
    </button>
 
    <p id='gfg'></p>
 
</body>
 
</html>


Output:

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

The position of (X, Y) means the coordinate of an element at the top-left point in a document. X represents the horizontal position and Y represents the vertical position. Use element.getBoundingClientRect() property to get the position of an element.

Table of Content

  • Button Position Retrieval on Webpage
  • Text Position Retrieval on Webpage

Similar Reads

Button Position Retrieval on Webpage

To obtain the position of buttons on a web page, we can use the getBoundingClientRect() method. This method provides us with information about an element’s size and position in the viewport. By using this method, we can obtain the X and Y coordinates of a button when it is clicked....

Text Position Retrieval on Webpage

...