How can I get the position of an element in JavaScript, specifically the X and Y coordinates of elements like `<img>` or `<div>`?

I’m looking for a reliable way to get position of an element in JavaScript so I can determine where these elements appear on the page.

Here is my go-to method when I need pixel-accurate positions relative to the viewport, especially useful for tooltips or image zoom features.

const el = document.getElementById('myElement');
const rect = el.getBoundingClientRect();
console.log('X:', rect.left, 'Y:', rect.top);

When I used this, I needed to position floating buttons relative to elements on a long scrolling page, this gives you the position relative to the full document.

const el = document.getElementById('myElement');
const rect = el.getBoundingClientRect();
const x = rect.left + window.scrollX;
const y = rect.top + window.scrollY;
console.log('Absolute X:', x, 'Absolute Y:', y);

On older jQuery-heavy projects, .offset() saved me a ton of time, it’s cross-browser safe and easy to read.

const offset = $('#myElement').offset();
console.log('X:', offset.left, 'Y:', offset.top);