Window width on Chrome and Firefox error

I have the following code:

function c() {
        var h = ($(window).height() - $('#maincontainer').outerHeight()) / 2;
        var w = ($(window).width() - $('#maincontainer').outerWidth()) / 2;

        $('#maincontainer').css('position', 'absolute');
        $('#maincontainer').css('top', h);
        $('#maincontainer').css('left', w);
    }

    $(window).resize(c);
    $(window).load(c);

The resize event works properly on every browser I tried but the load always returns a width value of 8px, putting the maincontainer div on the left border of the screen. This executes properly putting a div on the middle on the window only on IE8, failing on Chrome 22 and Firefox 16.

EDIT: The solution that seemed to work:

    $(window).ready(c);
    $(window).load(c);
    $(window).resize(c);

Also, the body should have width: 100%.

Upvotes: 0

Views: 1211

Answers (1)

PhonicUK
PhonicUK

Reputation: 13864

Instead of:

$(window).resize(c);
$(window).load(c);

do:

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

What's happening is you're asking for the size of the document before anything has loaded, so you get (almost) nothing. This does it as soon as the document is 'ready' and therefore gives you a more useful value.

You may also need to make your body 100% width and height and use that size instead of the window.

Upvotes: 1

Related Questions