Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript element position relative to screen

I need get position of an element relative to the screen or to the top left point of the window (point (window.screenX, window.screenY).

Why? I need desktop application to draw something on this position. I am able to get rect of the whole window and document, but I can't get the offset between top of the window and the top of the document.

Using window.outerHeight - window.innerHeight doesn't work, if user has opened, for example, debugging console of the browser.

Any thoughts? There are some articles about it on SP, but all of them works for me as relative to the document's view port.

Edit: other possible solution would be, to get screenX/Y values of the document

Thanks

like image 306
dakov Avatar asked Sep 23 '26 23:09

dakov


1 Answers

I've been looking around for the same thing, and surprisingly, this is tricky to implement.

There is a Firefox only solution -- window.mozInnerScreenX and window.mozInnerScreenY will give you the left and top of the viewport relative to the screen.

For other browsers, as far as I can tell, you'll need to listen to the first mouse or touch event. These events contain both screen and client coordinates of the event, which can be used to calculate the screen coordinates of the viewport.

innerScreenX = event.screenX - event.clientX;
innerScreenY = event.screenY - event.clientY;

Note that screen coordinates can be unexpected values (like -ve values) in case of multi monitor setups.

like image 107
aravindsagar Avatar answered Sep 26 '26 12:09

aravindsagar