Description
This is a (very) simple plugin that allows you to make any element on a web-page unobtrusively collapsable. It's something I find I end up doing quite a lot to clean up busy pages and hide away non-essential information, so I decided to write a jQuery plugin to do the hard work for me...
Usage
Using the plugin is pretty simple:
$('clickable element(s)').toggleControl( 'collapsable element(s)', options );
i.e. The following would make a title, control the toggling of a box of text (like this page)
$('#description-title').toggleControl('#description-body');
or you can use it to act on a series of paired elements - i.e. fieldsets in a form
$('fieldset.toggleable legend').toggleControl('fieldset.toggleable div');
These are the configurable options (passed in a JSON string):
- hide: [true/false]
- Hide the toggle-able element on page load, (default action is true).
- speed: ['slow'/'normal'/'fast' etc.]
- The speed of the sliding animations, (default setting is 'normal').
- event: ['click'/'mouseover' etc.]
- The event to observe for to fire the toggleControl, (default is 'click').
- openClass
- The CSS class for the control to take when its action is to 'open' the content, (default is 'toggle-open').
- closeClass
- The CSS class for the control to take when its action is to 'close' the content, (default is 'toggle-close').
Examples
This whole page uses the control, but here's a couple of examples using fieldsets. The only extra mark-up needed is a class of 'toggleable' as we use that to distinguish between other fieldsets. The code to activate them is as follows:
$('.toggleable legend').toggleControl('.toggleable div',{ speed:'slow' });
Simple eh?
Download
jquery.togglecontrol.js (uncompressed) - 1.6 Kb
jquery.togglecontrol.min.js (minified) - 624 bytes
jquery.togglecontrol.pack.js (packed) - 710 bytes
Or view the code itself...
/*
* jQuery toggleControl 1.0
*
* Copyright (c) 2008 Darren Oakley
*
* http://hocuspokus.net/
*
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
*/
;(function($) {
$.fn.extend({
toggleControl: function( element, options ) {
var defaults = {
hide: true,
speed: "normal",
event: "click",
openClass: "toggle-open",
closeClass: "toggle-close"
};
var options = $.extend(defaults, options);
return this.each( function( index ) {
var obj = $(this);
$(this).each( function ( i, toggle ) {
if ( options.hide ) {
$(toggle).addClass( options.openClass );
$(element).slideUp( options.speed );
} else {
$(toggle).addClass( options.closeClass );
}
$(toggle).bind( options.event, function(event) {
$(toggle).toggleClass( options.openClass );
$(toggle).toggleClass( options.closeClass );
$(element).eq(index).slideToggle( options.speed );
});
});
});
}
});
})(jQuery);