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…
- Doesn’t have a predefined width, and in the document it is inheriting the width from a parent element.
- 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 havingvisibility: 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:
- Grab and store the initial height before hiding the element
- Set an inline height to prevent the first reveal from jumping
- If we are revealing, and the element is visible, animate to zero height and then hide
- 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!
You should follow me on Twitter here I tweet about jQuery amongst the usual tweet-splurges!