Nov
26
2011

jQuery Collapsible Panel Plugin



Comments available as RSS 2.0

One of the things I find myself constantly doing with jQuery is making divs expand and collapse based on clicks on other elements. Collapsible panels are a great way of achieving progressive disclosure. I got sick of writing the same code on multiple pages so I wrote a plugin instead.

This creates an accordian style header which expands a linked panel when clicked.

Demo
Download

(function ($) {
    $.fn.extend({
        collapsiblePanel: function () {
            $(this).each(function () {
                var indicator = $(this).find('.ui-expander').first();
                var header = $(this).find('.ui-widget-header').first();
                var content = $(this).find('.ui-widget-content').first();
                if (content.is(':visible')) {
                    indicator.removeClass('ui-icon-triangle-1-e ui-icon-triangle-1-s').addClass('ui-icon-triangle-1-e');
                } else {                                       
                    indicator.removeClass('ui-icon-triangle-1-e ui-icon-triangle-1-s').addClass('ui-icon-triangle-1-s');
                }
 
                header.click(function () {
                    content.slideToggle(500, function () {
                        if (content.is(':visible')) {
                            indicator.removeClass('ui-icon-triangle-1-e ui-icon-triangle-1-s').addClass('ui-icon-triangle-1-e');
                        } else {                                       
                            indicator.removeClass('ui-icon-triangle-1-e ui-icon-triangle-1-s').addClass('ui-icon-triangle-1-s');
                        }
                    });
                });
            });
        }
    });
})(jQuery);

You also need a set structure for your panel (below).

<div class="ui-widget collapse">
    <div id="expander-demo-control" class="ui-widget-header">
        <span class="ui-icon ui-expander floatLeft">+</span>
        <span style="display: inline">Lime49 Expandy Widgets Inc.</span>
    </div>
    <div id="expander-demo" class="ui-widget-content">
        <p>Snap! the overstrained line sagged down in one long festoon; the tugging log was gone.</p>
 
	<p>"I crush the quadrant, the thunder turns the needles, and now the mad sea parts the log-line. But Ahab can mend all. Haul in here, Tahitian; reel up, Manxman. And look ye, let the carpenter make another log, and mend thou the line. See to it."</p>
 
	<p>"There he goes now; to him nothing's happened; but to me, the skewer seems loosening out of the middle of the world. Haul in, haul in, Tahitian! These lines run whole, and whirling out: come in broken, and dragging slow. Ha, Pip? come to help; eh, Pip?"</p>
    </div>
</div>

Call it using:

$().ready(function () {
    $('.collapse').collapsiblePanel();
});

Comments

Leave a Comment

Login using OpenID or enter your details below to leave a comment.

OpenID
Anonymous


Comment