ADVERTISEMENT
ADVERTISEMENT

Retrieve the position (XY) of an HTML element

Learn how to retrieve the position (XY) of an HTML element using JavaScript?
Submitted by Shahnail Khan, on April 01, 2022

At times there's a need to know the exact position of an element in HTML to make our websites responsive. The position refers to x & y coordinates. We can find the coordinates of an element at the top-left point in a document using JavaScript.

Let's say, the coordinate of an element is (25,6). Here, X=25 represents the horizontal position and Y=6 represents the vertical position.

We use XY.getBoundingClientRect() method in JavaScript to retrieve the position (XY) of an HTML element.

Example:

<!DOCTYPE html>
<html>
   <head>
      <title>Position(XY)</title>
      <!-- JavaScript code to retrieve position of an element -->
      <script>
         function Position(XY) {
             var pos = XY.getBoundingClientRect();
             document.getElementById('container').innerHTML ='X= ' + pos.x + ', ' + 'Y= ' + pos.y
         }
      </script>
   </head>

   <style>
      img{
      display: flex;
      align-items: center;
      }
   </style>

   <body>
      <div id="container"></div>
      <h2 class="click" onclick="Position(this)">IncludeHelp</h2>
      <nav class="topics" onclick="Position(this)">
         <a href="#">HTML</a>
         <a href="#">CSS</a>
      </nav>
      <img src="https://static.vecteezy.com/system/resources/thumbnails/000/180/409/small/software_enginner_1-01.png"
         onclick="Position(this)"/> 
   </body>
</html>

Output:

Retrieve the position (XY)

We can get the position of each element in the div container by clicking on a particular element in the output. For example, I clicked on the image and you can see its position is displayed at the top (X=8, Y=93.42500305175781).

JavaScript Examples »


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.