Categories
JavaScript Answers

How to Get an Element’s Top Position Relative to the Browser’s Viewport?

Spread the love

Sometimes, we may want to get an element’s top position relative to the browser’s viewport.

In this article, we’ll look at ways to get an element’s top position relative to the browser’s viewport.

Use the getBoundingClientRect Method

We can use the getBoundingClientRect method to get an element’s position relative to its viewport.

For instance, we can write:

const div = document.querySelector('div')  
const {  
  top: t,  
  left: l  
} = div.getBoundingClientRect();  
console.log(t, l)

We get the div with querySelector .

Then we call getBoundingClientRect on it to get an object with the top and left properties.

top has the position relative to the top of the viewport.

left has the position relative to the left side of the viewport.

Both are in pixels.

If we want to take scrolling into account, then we add the scrollY value to top and scrollX value to left .

For instance, we can write:

const div = document.querySelector('div')  
const {  
  top: t,  
  left: l  
} = div.getBoundingClientRect();  
const {  
  scrollX,  
  scrollY  
} = window  
const topPos = t + scrollX  
const leftPos = l + scrollY  
console.log(topPos, leftPos)

to include the scroll position with the element’s position.

Conclusion

We can get the element’s position relative to the viewport by using the getBoundingClientRect method.

2 replies on “How to Get an Element’s Top Position Relative to the Browser’s Viewport?”

Thanks a log, you made my day!
I tried $(this).offset().top but it always returned the same value, no matter what the parent elements positioning was set. I tried everything.
But this just works! 🙂

Leave a Reply

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