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"));
auto automatically computes the width such that the total width of the div fits the parent, but setting 100% will force the content alone to 100%, meaning the padding etc. will stick out of the div, making it larger than the parent. so setting the 'width' to 'auto' would be better? Yes, but that's the default anyway.
Set display to inline-block to make the div width fit to its content. Use position: relative and left: 50% to position its left edge to 50% of its containing element. Use transform: translateX(-50%) which will "shift" the element to the left by half its own width.
jQuery append() Method The append() method inserts specified content at the end of the selected elements. Tip: To insert content at the beginning of the selected elements, use the prepend() method.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With