views:

5041

answers:

5

How can I find the X Y coordinates of an HTML element (DIV) from Javascript if they were not explicitly set?

+6  A: 

That can be tricky depending on browser and version. I would suggest using jQuery and the positions plugin.

palehorse
Most of the positions plugin is now part of jQuery core. So you can just do $(element).offset({relativeTo: "body"}) - and it will give you the top and left of the object relative to the body.
Sugendran
Excellent, I haven't downloaded jQuery in a few months, good to know they rolled it in.
palehorse
A: 

I am not sure what you need it for, and such things are always relative (screen, window, document). But when I needed to figure that out, I found this site helpful: http://www.mattkruse.com/javascript/anchorposition/source.html

And I also found that the tooltip plugin someone made for jQuery had all sorts of interesting insight to x,y positioning tricks (look at its viewport class and the underlying support jQuery provides for it). http://bassistance.de/jquery-plugins/jquery-plugin-tooltip/

wulimaster
+3  A: 

You can use a library such as Prorotype or jQuery, or you can use this handy function:

It retuns an array.

myPos = findPos(document.getElementById('something'))
x = myPos[0]
y = myPos[1]


function findPos(obj) {

var curleft = curtop = 0;
if (obj.offsetParent) {
 curleft = obj.offsetLeft
 curtop = obj.offsetTop
 while (obj = obj.offsetParent) {
  curleft += obj.offsetLeft
  curtop += obj.offsetTop
 }
}
return [curleft,curtop];

}

Diodeus
You should give the attribution to quirksmode.org, that function looks very familiar.
Nouveau
+11  A: 

Here's how I do it:

// Based on: http://www.quirksmode.org/js/findpos.html
var getCumulativeOffset = function (obj) {
    var left, top;
    left = top = 0;
    if (obj.offsetParent) {
        do {
            left += obj.offsetLeft;
            top  += obj.offsetTop;
        } while (obj = obj.offsetParent);
    }
    return {
        x : left,
        y : top
    };
};
Andrew Hedges
A: 

Does any one have an idea how to get the x,y mouse position with a parent div

|----------------------------------------------------------
|                                                         |
|                                                         |
|                                                         |
|                                   x                     |
|                                                         |
|                                                         |
|----------------------------------------------------------

Basically the illustration indicate a div, with x being the current position of the mouse relative to its parent.