How to get x and y-axis positions for any HTML element in javascript?. Sometimes, We want to get x and y-axis coordinates for a given HTML element such as Div and img.
How to get x and y positions of HTML div element.
Javascript provides DOM API to access the object.
getBoundingClientRect()
in javascript returns size of an element and position related to view port.
Here is an Syntax
DOMRect obj=object.getBoundingClientRect()
DOMRect object contains the following properties.
- bottom
- height
- left
- right
- top
- width
- x
- y
All the values returned above are relative to the viewport.
<div id="test" style="width:150px; height:50px; border:1px solid red;">
</div>
function myFunction() {
var div = document.getElementById("test");
var domRect = div.getBoundingClientRect();
x = domRect.left;
y = domRect.top;
w = domRect.width;
h = domRect.height;
console.log(domRect)
}
Output
DOMRect {x: 8, y: 8, width: 152, height: 52, top: 8, …}
bottom: 60
height: 52
left: 8
right: 160
top: 8
width: 152
x: 8
y: 8
It is easy to get coordinates like x and y using this method.
Another way using adding
DOMRect.left + window.scrollX for X cordinates DOMRect.top + window.scrollY for Y cordinates
here is an example code get element offset in javascript
var div = document.getElementById("test");
const docrect = div.getBoundingClientRect();
console.log(docrect.left + window.scrollX),
console.log(docrect.top + window.scrollY)
Conclusion
Multiple ways to retrieve x and y positions of an HTML element using getBoundingClientRect() method in javascript.