Expand / Collapse with jQuery – Part II

Since my first post on the subject, I was introduced to a jQuery method called nextUntil(). I didn't realize the possibilities with this method until I got thinking about expand/collapse again. Where previously, I was using a wrapper to enclose the expandables/collapsables, that is no longer necessary.

The HTML

<h3>See this content?</h3>
<p>This is paragraph 1</p>
<p>This is paragraph 2</p>
<ul>
  <li>This is a list</li>
</ul>

The jQuery

$('h3').nextUntil('h3').hide();
$('h3').prepend('<span>+ </span>').css('cursor', 'pointer');
$('h3').click(function() {
    $(this).nextUntil('h3').slideToggle('fast');
    $(this).toggleClass('expanded');
    ($(this).children('span').html() == '+ ') ?
        $(this).children('span').html('- ') :
        $(this).children('span').html('+ ');
});

I even decided to include a little css directly in the jQuery, to make this technique even more "plug-n-play" into any given site.

Why follow me on Twitter?

  • I tweet about new technologies, services or libraries I find interesting
  • Yeah, sometimes I'll post a pet-peeve or rant about something trivial
  • If I discover something that made my web development life easier, I share it
  • I'll shout out any handy tip that I think might be useful to other devs


Tagged , .

Updated: 2011-03-24

Phil LaNasa follow us in feedly
  • admin

    To help with the "jiggle" effect, which is due to the fact that the "-" symbol has less width than the "plus" symbol, the follow CSS can help maintain a fixed width:

    h3 span { display: block; float: left; width: 9px; }

  • admin

    For those looking for a more "minified" version:

    $('h3').nextUntil('h3').hide();
    $('h3').click(function() {
        $(this).toggleClass('expanded').nextUntil('h3').slideToggle('fast');
    });