TheNorthFace TheNorthFace - 4 months ago 9
jQuery Question

jQuery show/hide animation, keep height on objects until animation is finished

I am building a HTML form which requires the possibility of some simple conditional fields to be toggled on/off. My problem is related to jQuery animation and object height not being preserved while the animation is in transition. This is causing a buggy jump in the animation transition.

See this fiddle to better understand the problem: https://jsfiddle.net/n3frxf6m/4/

When the checkbox is ticked, it replaces the default input field #4 with a conditional field #3.

I have tried a couple of methods, including replacing

display: none
to
visibility: visible
and using
opacity
in the script, but it doesn't solve the problem.

Is there an elegant way to make show/hide animations like this smooth?

<div style="width: 300px;">
<div>
<input type="checkbox" id="show_hide" /> Check me
</div>

<div style="float: left;">
<input type="text" value="Field 1" />
</div>

<div style="float: right;">
<input type="text" value="Field 2" />
</div>

<div id="hidden" style="display: none">
<input type="text" value="Field 3 (conditional field)" />
</div>

<div id="visible">
<input type="text" value="Field 4" />
</div>

<div>
<input type="text" value="Field 5" />
</div>
</div>

<script>
$('#show_hide').click(function() {
if ($(this).is(':checked')) {
$("#hidden").show(500);
$("#visible").hide(500);
} else {
$("#hidden").hide(500);
$("#visible").show(500);
}
});
</script>

Answer

the two first divs have CSS float property. So you need to clear this behaviour for the next divs. I added a third div after with clear:bothproperty, it gives:

https://jsfiddle.net/n3frxf6m/6/

Comments