Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you get a browser's document.body coordinates with respect to the screen?

Tags:

javascript

There must be a way of finding this. I need to figure out the coordinates of document.body with respect to a screenThis is as far I have got

I need to figure out the coordinates for the question mark in the image. This will be the position of the document's body with respect to the screen. The image gives a description of the properties I could use. Is it possible?

like image 529
dkulkarni Avatar asked Oct 09 '22 12:10

dkulkarni


2 Answers

bobbel on WebDeveloper.com suggests getting the width of the border by comparing the inner and outer window width, and then subtracting that from the inner-outer height difference to get the size of the window header for values you can add to screenX and screenY:

// compute width of borders
var borderWidth = (window.outerWidth - window.innerWidth) / 2;

// compute absolute page position
var innerScreenX = window.screenX + borderWidth;
var innerScreenY = (window.outerHeight - window.innerHeight - borderWidth) + window.screenY;

Granted, that's not guaranteed to be correct - it's entirely possible the user has a browser with a bar at the bottom, or window decorations that are different widths on the sides / bottom - but it's an accurate, practical workaround for the top-level browser window in every default browser/windowing configuration I can think of. (Of course, this won't work for pages in an iframe.)


The proper solution for this would be to propose a spec on the whatwg mailing list to make innerScreenX and innerScreenY a standard, as described in the discussion on Chromium issue 151983 regarding implementing an analogous value to mozInnerScreenX/Y for Chrome. It would appear that nobody has taken the time to do so, though (although there's this crazy proposal to implement an asynchronous API function to "calculate" it).

like image 160
Stuart P. Bentley Avatar answered Oct 13 '22 12:10

Stuart P. Bentley


As you've drawn it there,

x = window.screenLeft
y = window.screenTop + (window.outerHeight - window.innerHeight)

However, I would not trust this to be consistent across all browsers.

Edit:

In firefox you can use:

x = window.mozInnerScreenX
y = window.mozInnerScreenY

There may be an equivilent in Chrome. If you only need to support these two browser, you can use custom code for each.

like image 22
Oliver Avatar answered Oct 13 '22 11:10

Oliver