{ jQuery Expand/Collapse Menus }

I wrote this code for WordPress’s sidebar widgets, but it can be adapted to anything.

function sidebarHide(element) {
	// this function hides the ul
	// also calls sidebarPlus
	$('#sidebar ul ' + element +' ul').each(function() {
		$(this).hide('fast');
	});
	sidebarPlus(element);
	return false;
}
function sidebarShow(element) {
	// this function shows the ul
	// also calls sidebarMinus
	$('#sidebar ul ' + element +' ul').each(function() {
		$(this).show('fast');
	});
	sidebarMinus(element);
	return false;
}
function sidebarPlus(element) {
	// function appends a + to the title
	// this plus is a link to show the contents
	$('#sidebar ul ' + element + ' h2').each(function() {
		var text = $(this).text();
		var plus = text.lastIndexOf(" -");
		if (plus > 0) {
			text = text.substring(0, plus);
		}
		var link = '[a href="#" onclick="return sidebarShow('' + element + '');"] +[/a]';
		$(this).html( text + ' ' + link);
	});	
}
function sidebarMinus(element) {
	// function appends a - to the title
	// this minus is a link to hide the contents
	$('#sidebar ul ' + element + ' h2').each(function() {
		var text = $(this).text();
		var minus = text.lastIndexOf(" +");
		if (minus) {
			text = text.substring(0, minus);
		}
		var link = '[a href="#" onclick="return sidebarHide('' + element + '');"] -[/a]';
		$(this).html( text + ' ' + link);
	});	
}

And to use it

$(document).ready(function() {
	sidebarHide('#recent-posts');
	sidebarHide('#linkcat-2');
	sidebarHide('#linkcat-3');
});

Or, to just handle everything in the sidebar…

$(document).ready(function() {
	$('#sidebar ul li').each(function() {
		var n = $(this).attr('id');
		if (n != '') {
			sidebarHide('#' + n);
		}
	});
});

Leave a Reply

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