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.

Tags:

2 Comments

  1. 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; }

  2. For those looking for a more "minified" version:

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

Leave a Reply

Your email address will not be published. Required fields are marked *