Elegant way to collapse an empty div using jQuery?

Suppose I have a page with the following content:

<div><p>Some content</p></div> <div id="container"><p class="destroy">Some content that will go away.</p></div> <div if="footer"><p>Some footer content.</p></div> 

And some jQuery:

 jQuery(".destroy").click(function(){ jQuery(this).fadeOut('slow'); }) 

How to avoid the โ€œjumpโ€ of the footer after the contents disappear? I would like it to fit smoothly into place.

Here is the problem . Here, as I would like it to work (but without specifying a height).

Cautions:

  • #container will vary in width and height as the content will be dynamic.
  • The solution should be minimal, but readable.
  • jQuery and jQuery user interface are included.
  • Bonus points for an elegant universal solution (detect all empty divs and smoothly collapse them).
+4
source share
4 answers

You get a โ€œjumpโ€ because .fadeOut() sets display:none when the animation is complete.

Use .fadeTo() and reduce the transparency to 0 . You can then bind this with slideUp() to get the exact behavior you specify as โ€œhow I would like it to workโ€

 jQuery('.destroy').click(function(){ jQuery(this).fadeTo('slow', 0).slideUp(); }) 

Pudding Proof: http://jsfiddle.net/qJFnc/4/


If #container nothing else in #container , you can call slideUp() instead:

 jQuery('.destroy').click(function(){ jQuery(this).fadeTo('slow', 0, function() { jQuery('#container').slideUp(); }); }) 

More Pudding: http://jsfiddle.net/qJFnc/5/

+9
source

Animate it to zero and then remove the callback

demo: http://jsfiddle.net/qJFnc/2/

 jQuery('.destroy').click(function(){ jQuery(this).animate({height : 0}, function() { $(this).remove(); }) }) 

------------------ Edit:

To use the fade effect without CSS height, you need to use fadeTo () since it does not remove an element like fadeOut. Then, when you call back this slide, the element is up.

Demo: http://jsfiddle.net/qJFnc/10/

Updated Source:

 jQuery('.destroy').click(function(){ jQuery(this).fadeTo(500,0, function() { $(this).slideUp(); }) }) 
+1
source

Try it. This will get the dynamic height and set it to css.

http://jsfiddle.net/kQugU/2/

 jQuery('.destroy').click(function(){ jQuery('#container').css("height", jQuery('#container').height()); jQuery(this).fadeOut('slow',function(){ jQuery('#container').slideUp(); }) }) 
0
source

how about this?

 $(".destroy").click(function(){ $("#container").animate({opacity : 0},400,function(){ $(this).slideUp(100); }); }) 

http://jsfiddle.net/R779K/

The animate function has a callback that runs AFTER the main animation finishes. You can have it wherever you want.

Opacity only sets the opacity, leaving the display: the block is not damaged for the div, so when you disappear it looks like #content is gone and the footer slowly takes up empty space.

0
source

All Articles