width() immediately after div creation fails [kinda solved]

width() immediately after div creation fails [kinda solved]

Given is the following code and a HTML file with a <div id="container"></div> and an CSS file with ".class { width: 200px; }":

$(function () {
        var a = $('<div/>')
                .addClass('class')
                .appendTo($('#container'));
        alert(a.width());
        setTimeout(function () {
                alert(a.width());
        }, 0);
});

The first alert() reports a width that doesn't take '.class' into account, it reports almost the full browser width (Using FF 3). The second alert() reports the correct width.

Is there a way to get the correct width without such a timeout function? Like maybe forcing an update to all size calculations?

One thing that works is "a.css('left', '200px')", but I'd prefer not hard-coding the size in the code, but have it in a CSS file instead.

Thanks for any help!
    • Topic Participants

    • jlh