I want to know how to get the X and Y position of HTML elements such as img
and div
in JavaScript relative to the browser window.
If you want it done only in javascript, here are some one liners using getBoundingClientRect()
window.scrollY + document.querySelector('#elementId').getBoundingClientRect().top // Y
window.scrollX + document.querySelector('#elementId').getBoundingClientRect().left // X
The first line will return offsetTop
say Y relative to document.
The second line will return offsetLeft
say X relative to document.
getBoundingClientRect() is a javascript function that returns the position of the element relative to viewport of window.