Puneet
Puneet

Reputation: 585

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.

Upvotes: 4

Views: 2013

Answers (2)

SHASHA
SHASHA

Reputation: 90

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;

}

Upvotes: 1

Jeroen Baert
Jeroen Baert

Reputation: 1314

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;
}

Upvotes: 2

Related Questions