Using the jQuery .offset() function, you can get the coordinates of the top-left of the browser page:
var offset = $("selector").offset();
Combining that with the Javascript window.screenX and window.screenY window properties, you can calculate the position of the element as an offset from the top/left of the screen:
var screenY = offset.top + window.screenX;
var screenX = offset.left + window.screenY;
Note that window.screenX
and window.screenY
are standard in most browsers, but IE versions 8 and prior use window.screenTop
and window.screenLeft
, instead. If you need compatibility with IE8 or earlier, make sure to take that into account.
Also note that you might need to account for the current scroll position, in which case, you would use the jQuery .scrollTop() and .scrollLeft() methods and subtract from the offset value.
Unfortunately, this will not take window borders or toolbars into account. To do that, you can capture a mouse move and store the mouse position, which is given in actual screen coordinates.
The core of this solution is the following, which installs a one-time-use mouse handler to determine the actual screen coordinates of the page:
var pageX;
var pageY;
window.onmousemove = setMouseCoordinates;
function setMouseCoordinates (e) {
window.onmousemove = null;
pageX = e.screenX - e.clientX;
pageY = e.screenY - e.clientY;
}
Then, you can use those stored values to calculate the offset of any Javascript element:
x = pageX + elem.offsetLeft;
y = pageY + elem.offsetTop;
or jQuery element:
x = pageX + elem.position().left;
y = pageY + elem.position().top;
Check out the fiddle to see it in action: https://jsfiddle.net/mgaskill/bpqzct3f/