jQuery Sliding Animation – Copy & Paste!


jQueryanimationjQuery is quite beloved to my soul. I’ve used Javascript for years, but never extensively, preferring to rely on Flash/Actionscript to get me through animation.

And then the iphone/ipad happened, and they updated Actionscript to 3.0 (practically a whole new language from 2.0) and I discovered jQuery.

Now, I use jQuery in some form or another in almost all of my sites. It is a beautiful thing; quick, easy, impressive.

ANYWAYS, I’ve come across this little problem several times in my jQuerying years, and so I thought I’d do a quick mid-week post on the solution. [if you want the copy & paste, skip to the bottom]

Creating a Slide-Down Animation in jQuery

Normally to find the height of a Div, you’d write:


But to create a slide-down animation (at least, my way), you’ll need to know what the Div’s height SHOULD be if it was displaying all the information. This uses a different jQuery selector:

$('#divID2 p').height();

Yep. That’s right. Those two simple, tiny changes can mean the difference between making your animation work and it flopping around like a retarded seal on your computer. Notice, you have the selector ID [#divID2] plus the paragraph selector [p] after it. What is actually happening, is you are finding the height of the paragraph within the divID2.

Which means, you need to add the ‘<p></p>’ tags to your html so that there is a paragraph within that divID2 to find.

Also, this returns the actual number with no “px” attached.

And now, the code that creates that animation:

var totalheight = $('#divID2 p').height()+30; //I added 30px here for some spacing
// IF div is not showing
if ($('#divID2').css('height') == "0px"){
height: totalheight,
}, 300);
// IF div is showing already
height: '0',

#divID = Whatever you’re clicking on
#divID2 = Whatever div will be growing/shrinking
#divID2 p = The ‘<p></p>’ selectors within the Div. Without these, it WILL NOT WORK!