Retrieving the position of an HTML element relative to the browser window is something that we’ve to sometimes in our JavaScript web app.
In this article, we’ll look at ways to get the position of an HTML element relative to the browser window.
The getBoundingClientRect Method
The getBoundingClientRect
method is available with HTML element node objects to let us get the position of an element.
For instance, if we have the following HTML:
<div>
hello world
</div>
Then we can call getBoundingClientRect
by writing:
const div = document.querySelector('div')
const rect = div.getBoundingClientRect();
console.log(rect.top, rect.right, rect.bottom, rect.left);
We get the div element with querySelecttor
.
Then we call getBoundingClientRect
to get the position.
left
and top
has the x and y coordinates of the top left corner of the element.
right
and bottom
has the x and y coordinates of the bottom right corner of the element.
Element’s Position Relative to the Whole Page
We’ve to add scrollX
and scrollY
to get the element’s position relative to the whole page.
For instance, we can write:
const div = document.querySelector('div')
const getOffset = (el) => {
const rect = el.getBoundingClientRect();
return {
left: rect.left + window.scrollX,
top: rect.top + window.scrollY
};
}
console.log(getOffset(div));
scrollX
returns the number of pixels that the document is currently scrolled horizontally.
And scrollY
returns the number of pixels that the document is currently scrolled vertically.
offsetLeft and
offsetTop
offsetLeft
and offsetTop
lets us get the position of the upper left corner of the element relative to the nearest parent.
For block-level elements, offsetTop
, offsetLeft
describe the border-box of an element relative to the offsetParent
.
For inline elements, offsetTop
, offsetLeft
describe the positions of the first border-box.
For instance, we can use it by writing:
const div = document.querySelector('div')
console.log(div.offsetLeft, div.offsetTop);
Conclusion
We can get the position of an element with various properties in JavaScript.