JavaScript

How to get the element position on the screen – XY coordinates

November 9, 2021

How to get the element position on the screen – XY coordinates

In this article we’ll learn how to get the element position on the screen using JavaScript, which will give us the exact coordinates the element is in.

get the element position on the screen cover

Hey you programmer, let’s learn something new?

Watch this content on YouTube:

With JavaScript we can do almost everything in the browser, getting the position of an element is one of its features

For this we will use a method called getBoundingClientRect and access its properties

They will contain values of the coordinates of where the element is, look at the code:

<!DOCTYPE html>
<html>
 <head>
  <title>Como obter a posição do elemento na tela</title>
 </head>
 <body>
  <div id="box"></div>
 </body>
</html>

And the CSS:

#box {
 width: 50px;
 height: 50px;
 position: absolute;
 top: 100px;
 left: 45px;
 background-color: red;
}

It will print the following on the screen:

element box javascript

And now we use JavaScript to find the position of the element with id box, as it is our HTML:

let el = document.getElementById('box');

let elCoordinates = el.getBoundingClientRect();

console.log(elCoordinates);

Quite simply, we select the element and then insert the value of the getBoundingClientRect method into a variable

This variable now contains the positions of the element and its x and y coordinates, see console.log output:

Now that we get the position of the element on the screen, just use it as needed to solve your problem 

Conclusion

In this article we learned how to get the element position on the screen

Basically we select the element we want to get the positions

And then with the help of the getBoundingClientRect method, we have accesses to properties that give us the coordinates

And not only that, its top, left, right and bottom distances

Do you want to learn more about JavaScript? Click here!

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x