6

In the script I'm working on, I'm appending markup for a feedback form to the body and then centering that element (a DIV) on screen with jQuery. In the code sample below, form_code holds my form markup. The defined CSS styles for #feedback_form explicitly define a width. However, the calculation for width() called immediately after appending is calculating wrong, returning a dimension almost equal to the entire width of the page.

If I alert the width with console, even seconds later, it calculates correctly. Never run into this before, can somebody shed some light on this?

jQuery('body').append(form_code);
alert(jQuery("#feedback_form").css("width"));
Mike
  • 3,331
  • 2
  • 18
  • 22

2 Answers2

18

Your Javascript code is running in a different thread to the one that renders the HTML. If you query the width immediately after adding new code the render thread won't have had time to relayout the page so you get the old, or possibily an intermediate, width.

I'm not sure if this is the case with newer browsers but certainly old ones were co-operatively multitasking so the page wouldn't update until you explicitly paused to allow it to update.

If you use the following code you'll find it works because the zero second pause actually allows the browser to process the rerender event.

function show_width() {
    alert(jQuery("#feedback_form").css("width"));
}
setTimeout(show_width, 0);
Andrew Wilkinson
  • 10,682
  • 3
  • 35
  • 38
0

What are you looking to do? Your code is adding element(s) to the DOM, which takes time. Are you trying to process something based on the width, etc... after you add your form_code?

TNC
  • 5,388
  • 1
  • 26
  • 28