Possible to get upper left coordinates of a Div in Jquery

In Jquery let’s say I want to get the upper left coordinates of a div

<div id=“coolDiv”>text here</div>

topPos=$(coolDiv).top;
leftPos=$(coolDiv).left;

Is that possible at all?

I don’t know if jQuery provides a wrapper for this, but finding the coordinates of an element in the page is a little more complicated than looking at a property

function findPosX(obj) {
    var curleft = 0;
    if (obj.offsetParent) {
        while (1) {
            curleft+=obj.offsetLeft;
            if (!obj.offsetParent) {
                break;
            }
            obj=obj.offsetParent;
        }
    } else if (obj.x) {
        curleft+=obj.x;
    }
    return curleft;
}

function findPosY(obj) {
    var curtop = 0;
    if (obj.offsetParent) {
        while (1) {
            curtop+=obj.offsetTop;
            if (!obj.offsetParent) {
                break;
            }
            obj=obj.offsetParent;
        }
    } else if (obj.y) {
        curtop+=obj.y;
    }
    return curtop;
}

I found something that does it:

$(‘#mainMenu’).position().left

will return the left coordinates of the div named main Menu

nice!

Are ya sure?

The position relative to your parent is not the same as position within the window

Your right, for some reason it works in Firefox but not IE, I wish there was an easier way… I’ll use you’re functions then thanks for that!

How would I pass in the id of mainmenu into that?

Sorry i’m not too familiar with Javascript.

The $(‘#mainMenu’).position().left method works in most cases except for if your Div is nested alot in other divs, as far as I can tell if your site structure is pretty basic it works, in IE 7 and FF 3.0 at least…

menu = document.getElementById(‘mainMenu’);
x = findPosX(menu);
y = findPosY(menu);

ok, got you, thanks for the help

$(‘#mainMenu’).position().left
really good :-). jQuery. write less, do more :slight_smile:

:cool:

Yeah it works great in most situations except I just realized it’s not perfect in Chrome.

I think $(‘#mainMenu’).offset().left should work for you to get left positioning.
offset() function return position of the element relative to the document.