Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting screen coordinates to page coordinates

Given the screen coordinates of a point, is there some way to calculate the coordinates of that point on the actual page of the browser? Here is a small image illustrating the problem

Here is a small image illustrating the problem. I have a point(ScreenX,ScreenY) and want to convert it to point(PageX,PageY).

From what I have seen there is no way to calculate the height of the browser toolbar etc, so window.innerHeight and window.outerHeight do not really help here.

Anny help is appreciated :-)

like image 933
Rambazamba Avatar asked May 15 '26 23:05

Rambazamba


1 Answers

#div-id {
  border: 1px solid red;
  width: 100px;
  height: 100px;
  display: inline-block;
  position: absolute;
  left: 100px;
}
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

</head>
<body>

<div id="div-id"> POSITION </div>

<script>
var element = document.getElementById('div-id');
var position = element.getBoundingClientRect();
var x = position.left;
var y = position.top;

var XLoc = window.screenX;
var YLoc = window.screenY;
var toolbarHeight = window.outerHeight - window.innerHeight;

console.log('Div position : X :',  x ,'--Y : ', y);


console.log('Window position: X:',  XLoc ,'-- Y : ', YLoc);

console.log('Actual position of DIV from scrren -  X:',  (x + XLoc) ,'-- Y : ', ( y + YLoc + toolbarHeight ) );

</script>
</body>
</html>

use below properties for the requirements.

window.screenX

window.screenY

like image 50
Shiv Kumar Baghel Avatar answered May 18 '26 11:05

Shiv Kumar Baghel