views:

497

answers:

3

I'm trying to get the screen coordinates (that is, relative to the top left corner of the screen) of an element in a browser window. It's easy to get the size and position of the window (screenX, screenY) and it's easy (with jQuery) to get the offset of the element ($('element').offset().left).

However, I need to know how many pixels it is from the element all the way to the corner of the screen. I've found some things that appear to be specific to IE, but I'd like this to work in as many browsers as possible.

Edited to add a picture: alt text

+1  A: 

I don't think this is possible.

The element coordinates are relative to the top left corner of the rendered page.

The window coordinates are relative to the screen.

There is, to my knowledge, nothing that relates the top left corner of the rendered page to the top left corner of the window. So there's no way to account for borders, scrollbars, chrome, etc. So I think you're sunk on this one.

jvenema
That really sucks.
jerwood
+2  A: 

window.screenX/Y are not supported on IE. But for other browsers, a close approximation of position is:

var top = $("#myelement").offset().top + window.screenY;
var left = $("#myelement").offset().left + window.screenX;

Exact position depends on what toolbars are visible. You can use the outer/innerWidth and outer/innerHeight properties of the window object to approximate a little closer.

IE doesn't provide much in the way of window properties, but oddly enough, a click event object will provide you with the screen location of the click. So I suppose you could have a calibration page which asks the user to "click the red dot" and handle the event with

function calibrate(event){
    var top = event.screenY;
    var left = event.screenX;
}

Or possibly use the mouseenter/leave events using the coordinates of that event to calibrate. Though you'd have trouble determining if the mouse entered from the left, right, top, or bottom.

Of course, as soon as they move the screen you'll need to recalibrate.

For lots more on browser property compatibilities see PPK's Object Model tables.

Joel Potter
Can you get the position of the mouse cursor relative to the element it's in, as well as the screen coords? Then calibration could really work.
jerwood
Hmmm, thinking about this more, I understand better what you meant. I think it would definitely work to calibrate, and it would only need to be redone if they changed their browser chrome.
jerwood
Thanks for pointing me in the right direction. Thinking in terms of doing this IN a click event in the page makes all the difference. With that context I can calculate the browser chrome offsets. And this works in IE.This is what I've come up with: (event.screenY - event.pageY) + $('#element').offset().topWhich gives the screen Y of the element in question.
jerwood
A: 

Coordinates of the cursor relative to the screen

http://java.pakcarid.com/Cpp.aspx?sub=386&ff=3064&topid=40&sls=25

lois