Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elegant way to collapse an empty div with 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 do avoid the 'jump' of the footer once the content goes away? I would like it to smoothly slide into place.

Here's the problem. Here's how I would like it to work (but without specifying a height).

Caveats:

  1. The #container will vary in width and height, as it's contents will be dynamic.
  2. The solution must be minimal but readable.
  3. jQuery and the jQuery UI are included.
  4. Bonus points for an elegant universal solution (detects all empty div's, and smoothly collapses them).
like image 599
Luke The Obscure Avatar asked Sep 15 '11 17:09

Luke The Obscure


2 Answers

You get the "jump" because .fadeOut() sets display:none when the animation is completed.

Use .fadeTo() instead and fade the opacity to 0. You can then chain that with slideUp() to get the exact behaviour your specified as "how I would like it to work"

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

Proof of the pudding: http://jsfiddle.net/qJFnc/4/


If there's nothing else in #container, you could call slideUp() on that instead:

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

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

like image 165
Shawn Chin Avatar answered Oct 19 '22 09:10

Shawn Chin


Animate it to zero and then remove on 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 affect with no CSS height you need to use the fadeTo() as it doesnt remove the element like fadeOut does. Then on the callback of that slide the element up.

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

Updated Source:

jQuery('.destroy').click(function(){
    jQuery(this).fadeTo(500,0, function() {
        $(this).slideUp();
    })
})
like image 27
wesbos Avatar answered Oct 19 '22 09:10

wesbos