Reputation: 2100
I create a div dynamically and then should change css properties based on the width of that div:
function test(divID){
//some actions - creating the div 'tbl' structure
$('#'+divID).html(tbl);
var tw = $('#'+divID).width() + 80;
$('.page').css("width", tw+"px");
}
It all works fine in Chrome, but not very stable in FF - sometimes it calculates var tw before the div is rendered and returns its zero width.
How can I sync these events, i.e. measure the width of that div after it has been rendered? I cannot use onLoad, because the whole DOM is loaded before that.
Thanks
Upvotes: 0
Views: 634
Reputation: 3281
You can force a reflow of content (making sure the new content is in the DOM) by calling for the offsetWidth
on an object.
Here your code would look like:
function test(divID){
//some actions - creating the div 'tbl' structure
$('#'+divID).html(tbl);
$('.page')[0].offsetWidth; // force reflow;
var tw = $('#'+divID).width() + 80;
$('.page').css("width", tw+"px");
}
You wouldn't want to do this in a huge loop as page reflows are relatively expensive operations. instead, you could run a loop that creates divs, then call offsetWidth
, then another loop to assign widths.
See "Force Reflow" in CSS transitions in Bootstrap for more info.
Upvotes: 1