Using javascript, I’m creating some html content–some nested divs that are styled via a style sheet.
After calling $(container).html(dhtmlString) I the attempt to do some calculation for layout purposes. However the values I am getting back from jQuery do not match the expected values when running in Safari and Chrome.
In code:
var someHtml = ...;
$(".Container").html(someHtml);
var containerWidth = $(".Container").width(); // properly reports 800
var nestedDivWidth = $(".NestedDiv").width(); // incorrectly reports 800
I’m expecting NestedDiv to be around 450px (thats what it is in the style sheet). On FF and IE, this works fine, but in Safari and Chrome it doesn’t.
I suspect there is a timing issue with how the DOM is updating in safari/chrome.
When the content is actually rendered to the browser, the developer element inspector does show the proper width.
I’m using jquery 1.4.2 (i’ve already tried 1.4.3 as well), with no luck.
If you run into this kind of thing, it’s probably worth giving the browser a moment to process the HTML change:
That basically does a thread yield to the browser’s rendering engine. More specifically, it schedules a timer to be called back as soon as possible (most browsers won’t call back faster than 10ms, but that’s up to them), which gives the rendering thread (if there is one, some browsers use one thread for everything, in which case you really need the above) a chance to catch up. Since the function closes over any data in the enclosing scope, it’s pretty painless from a coding perspective to carry on your logic within the function rather than after it. (Note that any statements after the
setTimeoutwill happen before the code in the function you gave tosetTimeout; that’s the whole point of moving the logic into the function.)