Monthly Archive for November, 2008

jQuery Show/Hide for Wordpress Sidebar Widgets

Here’s some handy jQuery code to show/hide menu items in Wordpress’s sidebar.

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 + '\');">' + text + ' +</a>';
		$(this).html(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 + '\');">' + text + ' -</a>';
		$(this).html(link);
	});	
}
 
 
$(document).ready(function() {
 
	$('#sidebar ul li').each(function() {
		var n = $(this).attr('id');
		if (n != '') {
			sidebarHide('#' + n);
		}
	});
 
});

Javascript CheckAll/UncheckAll

For posterity:

function checkAll(fieldname, check) {
 
	check = typeof(check) != 'undefined' ? check : true;
 
	var fn_length = fieldname.length;
	var F = document.forms[0];
	for (var i = 0; i < F.elements.length; i++) {
		var element = F.elements[i];
		if (element.type == "checkbox") {
			var n = element.name;
			if (n.substr(0, fn_length) == fieldname) {
				var checkbox = document.getElementsByName(n);
				checkbox[0].checked = check;
			}
		}
	}
 
	return false;
}

And to use:

<a href="#" onclick="return checkAll('states');">Check All</a> |
<a href="#" onclick="return checkAll('states', false);">Uncheck All</a>

This assumes that your checkboxes are prepped for array structure in PHP. This means that you have a bunch of checkboxes with names like “states[1]” and “states[34]” …