EN
JavaScript - get the position of HTML element (X and Y coordinates)
1
answers
0
points
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
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
andmargin
before getting the coordinates, but there is1px
offsetfrom the image size because of the container border.
References
0 comments
Add comment