The width of the DIV immediately after adding is not calculated correctly

In the script I'm working on, I add markup for the feedback form for the body, and then center this element (DIV) on the screen using jQuery. In the code sample below, form_code contains my form markup. Certain CSS styles for #feedback_form explicitly define the width. However, the calculation for width (), called immediately after the addition, is calculated incorrectly, returning a size almost equal to the entire width of the page.

If I warn about the width using the console, even after a few seconds, it will calculate correctly. Never come across this before, can anyone shed some light on this?

jQuery('body').append(form_code); alert(jQuery("#feedback_form").css("width")); 
+6
jquery
source share
2 answers

Your Javascript code runs in a different thread with the one that renders the HTML. If you request a width immediately after adding a new code, then there will not be time in the rendering stream to relay the page so that you get the old or, possibly, intermediate width.

I'm not sure if this is the case with newer browsers, but of course the old ones were multi-tasking joint, so the page did not refresh until you explicitly stop to let it refresh.

If you use the following code, you will find that it works because a zero second pause actually allows the browser to handle the reverder event.

 function show_width() { alert(jQuery("#feedback_form").css("width")); } setTimeout(show_width, 0); 
+18
source share

What are you going to do? Your code adds elements (elements) to the DOM, which takes time. You are trying to process something based on width, etc. After you add your form_code?

0
source share

All Articles