Sometimes, we want to get an object’s absolute position on the page in JavaScript.
In this article, we’ll look at how to get an object’s absolute position on the page in JavaScript.
How to get an object’s absolute position on the page in JavaScript?
To get an object’s absolute position on the page in JavaScript, we can use the getBoundingClientRect
method.
For instance, we write
const logo = document.getElementById("hlogo");
const logoTextRectangle = logo.getBoundingClientRect();
console.log(logoTextRectangle.left);
console.log(logoTextRectangle.right);
to select the element with getElementById
.
Then we get an object with the position values with the getBoundingClientRect
method.
Next, we get the left
and right
position values from the object returned by getBoundingClientRect
.
Conclusion
To get an object’s absolute position on the page in JavaScript, we can use the getBoundingClientRect
method.