Collapsible Sections with jQuery

I’ve previously posted about how to collapse sections using JavaScript in an HTML Container.  It’s a pretty cool trick, but the experience isn’t really that great because it’s jarring.  Also, the tax on the developer is high since you have to measure pixel perfect sections and deal with 0px height sections in your design mode.  Today, I’m going to show how to do this using jQuery that’s both much easier and more engaging.

The first thing we have to do is find the section id that we want to hide.  To do that, run the document like normal, right click on the section in Chrome or Firefox, and click Inspect Element.  The ID will be displayed in one of two places, highlighted in the screenshot below.

Note: The numbers shown in this screenshot are totally fictional and just random numbers.

Armed with that information, go back to design mode and add an HTML Container to where you want the +/- control box to be.  It’ll have the following simple code:

<img id=’more’ style=”cursor:pointer” width=12 src=”../images/plus.gif”>

Note: The image reference should be to whatever you want to use to display a “more” action, like a + sign.

Next, add an HTML Container anywhere on the page with the following code:

<script src="">
$(document).ready(function() {

 $('#more').click(function () {
         if ($('#K8').is(":hidden")) {
$('#more').attr('src', '../images/minus.gif');}
         else {
$(’#more').attr(‘src’, '../images/plus.gif’);}


Note: See the jQuery post about how to install jQuery locally if your web server doesn’t allow cross site scripting.

The basic strategy is to first hide the section at page load.  This is something we can’t do without jQuery, which is why the previous solution required starting at 0px height.  Next, we simply monitor the ‘more’ image and when it’s clicked, we check if the target section is already hidden.  If it is, then slideDown() and if it isn’t, then slideUp().  Also, toggle the image to flip between the + and – sign.  The effect is a smooth animation that’s engaging and inviting to the user.

The code here is easier, there’s no measuring section heights like the previous solution, and you end up with a sweet animation.

I’ll come back later and post a video (I hope).

Dynamic Sections
With a little bit of coding, we can also extend this to dynamically control sections based on page groupings.  For more details, check out this excellently detailed blog post at

You may also like...