Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find the position of an HTML element relative to the entire desktop screen using JavaScript?

How do i find the X,Y coordinates of a particular html element ( eg. div, table, lable, etc...) relative to the desktop screen (i.e. outside the browser window) using JavaScript?

I can find the height and width of the element by using offsetHeight and offsetWidth, but can't find anything that can give me exact X,Y coordinate of the element relative to the user’s entire desktop screen.

like image 577
Puneet Avatar asked Sep 17 '25 13:09

Puneet


2 Answers

I think you have to follow the tree up, through the parents, and keep adding the offsets, like described here:

http://bytes.com/topic/javascript/answers/90547-how-get-absolute-position-element

function getY( oElement )
{
    var iReturnValue = 0;
    while( oElement != null ) {
        iReturnValue += oElement.offsetTop;
        oElement = oElement.offsetParent;
    }
    return iReturnValue;
}
like image 170
Jeroen Baert Avatar answered Sep 20 '25 04:09

Jeroen Baert


I don't think it is not possible even it is quite simple.

  1. Find the position of browser relative to screen
  2. Find the element position relative to view port.
  3. Add the coordinates and you will have the output you want

Follow the piece of code I written:

var element = document.getElementById("ID of the element");// you can use any method to find the element ..
var position = getPosition(element);
function getPositions(obj)
{
        var p = [];
        var position =  obj.getBoundingClientRect();
        p[0] = window.screenX + position.left;
        p[1] = window.screenY + position.top;
        p[2] = position.width;
        p[3] = position.height;
        return p;

}
like image 37
SHASHA Avatar answered Sep 20 '25 04:09

SHASHA