Garik
Garik

Reputation: 151

When is the new style applied in an HTML Form

It's very interesting how does browser engine works in this situation, because I test it in IE, Firefox and Chrome and they all works differently. For example:

<style>
.parent{
width:100px;
}
.expand{
width:200px;
}
</style>

<div class="parent">
<div class="child"></div>
</div>

<input type="button" id="btn" />

<script>
//onready
$('#btn').click(function(){
$('.parent').toggleClass('expand');
alert($('.child').width());
});
</script>

The problem is in chrome. I don't know why but ('.child').width() is always old value, but not a new width of his parent. When and how does recalculating for width works?

Upvotes: 2

Views: 67

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075079

When and how does recalculating for width works?

As you've found, it can be browser-dependent.

If you give the browser a moment to do its work by releasing the JavaScript thread, you see the new value:

$('#btn').click(function(){
    $('.parent').toggleClass('expand');
    setTimeout(function() {
        alert($('.child').width());
    }, 0);
});

Live Example | Source (see also the notes below)

The delay won't really be 0 milliseconds, of course, but it'll be very brief indeed.


Separately, this line

$('parent').toggleClass('expand');

should be

$('.parent').toggleClass('expand');

(Note the leading .)

...and I should note that for me, on Chrome for Linux, it works without the timeout: Example | Source

Upvotes: 7

Related Questions