views:

811

answers:

3

When I alert the value .position().left, it returns 0 on Chrome. With other browsers it returns the actual number. Why does this happen?

A: 

Webkit can be too fast sometimes, but it's often taken care of in jQuery. You can debug using something like:

var v, elem = $('.myElement');
window.setTimeout(function() {
    v = elem.position().left;
    console.log(v);
    if (v) {
        return false;
    }
    window.setTimeout(arguments.callee, 1);
}, 1);

This will check if and when the position is available. If you are logging "0" in infinity, the position().left is "never" available and you need to debug elsewhere.

David
great, thanks for help David.
goksel
+1  A: 

I had the same problem.. I fixed it using:

.offset().left

instead. But be aware that are not the same: http://api.jquery.com/offset/

.position().left worked in Chrome in some tests I did, using a similar approach than David (the value was available since the first try). In my "real" application failed even reading the position on click event (which may eliminate any loading speed problem). Some comments (in other forum) say it may be related to the use of display:inline-block. However I couldn't reproduce the problem using inline-block. So it may be other thing.

lepe
A: 

By reading comments from http://api.jquery.com/position/, there are several ways to fix this. The one I found working is

Ajaho [Moderator] :This plugin function fixes problems with wrong position in Chrome

jQuery.fn.aPosition = function() {
thisLeft = this.offset().left;
thisTop = this.offset().top;
thisParent = this.parent();
parentLeft = thisParent.offset().left;
parentTop = thisParent.offset().top;
return {
left: thisLeft-parentLeft,
top: thisTop-parentTop
}
}