Search

SlideDown Animation Jump Revisited

Posted on 15th April 2009 — When using slideDown depending on the layout of your page, you could still see the jumping effect, regardless of whether you fix the padding around the element.

Watch

Watch Animation Jump Revisited screencast (Alternative flash version)

QuickTime version is approximately 20Mb, flash version is streaming.

View the demo used in the screencast

Understanding the Problem

Similarly to before the animation would jump when it gets towards the end. However, this time the problem can’t be fixed by moving the padding around.

The problem is actually due to an incorrect height being determined, which is triggered by a number of factors. The element being animated…

  1. Doesn’t have a predefined width, and in the document it is inheriting the width from a parent element.
  2. Is changed to position: absolute and as such the margins around the top and bottom no longer collapse. This is to determine the height by bringing it back in to view (whiles having visibility: none set) but not affecting the flow of the page.

As you’ll see in the screencast, just setting a width doesn’t quite get the correct height.

So we can’t just use CSS to fix the jump, we need to write slightly different jQuery.

Fixing the Problem

The task requires us to:

  1. Grab and store the initial height before hiding the element
  2. Set an inline height to prevent the first reveal from jumping
  3. If we are revealing, and the element is visible, animate to zero height and then hide
  4. Otherwise, show and animate the height to the initial captured height
var $div = $('#test');
var height = $div.height();
$div.hide().css({ height : 0 });

$('a').click(function () {
  if ( $div.is(':visible') ) {
    $div.animate({ height: 0 }, { duration: 2500, complete: function () {
        $div.hide();
      } 
    });
  } else {
    $div.show().animate({ height : height }, { duration: 2500 });
  }
    
  return false;
});

Wrapping Up

I’m going to post a bug on the jQuery dev site, and I’ve had a play around the code to be able to accurately establish the height of a hidden element – it’s not easy.

Hopefully this might be one of the last times we run in to the jump problem!