JQuery function not working as expected

Posted by Mike on Stack Overflow See other posts from Stack Overflow or by Mike
Published on 2010-03-27T03:18:53Z Indexed on 2010/03/27 3:23 UTC
Read the original article Hit count: 314

Filed under:
|

I've written a little function to position a logo midway between the left hand side of the browser window and the (centered) navigation menu. The menu items are populated from a database, with the first item given the id item0.

function positionLogo(){
    var $menuleft=0;
    var $element=document.getElementById('item0');
    if ($element.offsetParent) {
        do {
            $menuleft+=$element.offsetLeft;
        } while ($element=$element.offsetParent);
    }
    var $logoleft=($menuleft/2)-130; // As logo is 260px wide
    if ($logoleft<0) {
        $logoleft=0;
    }
    $('#logo').css('left',$logoleft);
}

$(document).ready(function(){
    positionLogo();
});

$(window).resize(function(){
    positionLogo();
});

This works fine when the window is resized, but when it first runs when the page is loaded, the position it sets is about 20px too far right (ie $logoleft is 20 more than it should be). As soon as the page is resized it jumps into the correct position.

Haven't got it live anywhere at the moment but does anyone have any ideas? Thanks!

© Stack Overflow or respective owner

Related posts about jQuery

Related posts about css-positioning