Ibrahim D. Ibrahim D. - 8 months ago 86
Javascript Question

HTML Element location relative to screen

I am trying to get the location of a div element relative to the screen.
I read every where and still can't find a solution to this, my code currently is:

var myElement = document.getElementById('pi');
var myElement2 = document.body;

alert (myElement.offsetTop + ',' + myElement.offsetLeft);
alert (myElement2.offsetTop + ',' + myElement2.offsetLeft);
alert (window.screenX);


All i get is 8,8 for my div element which is not really the location.

HTML code:

<body>
<div id=pi >fffddd</div>
</body>

Answer Source

Assuming the left edge of the browser is the left edge of the body and all of the difference between window.innerHeight and window.outerHeight is above the body you can get a lot closer to what you are asking for. There are additional assumptions being made here with regards to multi-display setups.

xPos = myElement.offsetLeft + window.screenX;
yPos = myElement.offsetTop + window.screenY + window.outerHeight -

window.innerHeight;

let myElement = document.body,
    xPos = myElement.offsetLeft + window.screenX,
    yPos = myElement.offsetTop + window.screenY + window.outerHeight -
 window.innerHeight;

alert ( xPos + ',' + yPos );

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download