SiteKickr Web Development

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.