Explain Codes LogoExplain Codes Logo

How to get an element's top position relative to the browser's viewport?

javascript
getboundingclientrect
positioning
viewport
Nikita BarsukovbyNikita Barsukov·Feb 18, 2025
TLDR

To swiftly retrieve the position of an element within the viewport, you can use element.getBoundingClientRect().top. This function gives you the vertical coordinate, or "Y position", of the element:

const topPos = document.querySelector('.element').getBoundingClientRect().top; console.log(topPos); // Prints whatever the element's top position is. It's actually that simple!

In this chunk of code, topPos is holding the distance of the element from the viewport's top edge. This can be handy for layout calculations and triggering events based on scroll position.

Dealing with page scrolling

Keep in mind that getBoundingClientRect() returns the position relative to the viewport, not the entire page. So, if you've scrolled down the page, your element's position within the viewport will change. So if you need an absolute position, regardless of scrolling, you need to consider the overall scroll position as follows:

const rect = document.querySelector('.element').getBoundingClientRect(); const absTopPos = rect.top + window.pageYOffset; console.log(absTopPos); // Prints accurate element's top position even if you've scrolled halfway to Narnia.

Compatibility across the browser-verse

While our friendly neighborhood getBoundingClientRect() is consistently supported across browsers, it's always worth considering potential browser-configuration differences. Some "ancient" browsers (looking at you, IE) may require fallbacks such as document.documentElement.scrollLeft/scrollTop.

Making peace with viewport sizes

There's also the not-so-minor issue of viewport sizes. These can change dynamically, often due to users resizing their windows or flipping their mobile devices. Event listeners for resize or orientationchange events can help in persistently accurate positioning.

Manual mode with offsetTop and offsetParent

If for some reason you can't use getBoundingClientRect(), you are not entirely out of options. You can calculate the distance to an element using offsetTop and offsetParent properties as follows:

function findElementTopPos(element) { let totalOffset = 0; do { totalOffset += element.offsetTop || 0; element = element.offsetParent; } while(element); return totalOffset - document.body.offsetTop; }

Just keep in mind you'll always be thankful for getBoundingClientRect() after this.

jQuery enthusiasts, we've got you covered

For those more comfortable with jQuery, the .offset() method is no stranger:

let topPos = $('.element').offset().top; console.log(topPos); // jQuery here like: "hold my beer, got this!"

However, do consider that this is heavier than vanilla JavaScript approaches, and may not always be the optimal solution.

Necessity of accurate positioning

Remember, a precise positioning can make or break user experiences on your web application. From sticky headers that should remain visible, to fixed-position toolbars that shouldn't obstruct your content, the savvy use of element positioning can greatly enhance your website's interface.