Categories
JavaScript Answers

How to get an object’s absolute position on the page in JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *