jQuery Expand All

by Trick.

Here’s another lunchtime jQuery snip­pet as the last one proved semi-popular. This one came about today as I needed to expand on an exist­ing expand/collapse func­tion­al­ity to allow users to expand or col­lapse all of the objects with this func­tion­al­ity.

What had already been done was set a jQuery func­tion to react on the pres­ence of the .expanded class. The way it works is very sim­ple, jQuery grabs all the ele­ments with the .expand­able class and then using the :first selec­tor it tests the first one to see whether it is expanded or not. Then depend­ing on the out­come it applies or removes the .expanded class.

function toggle_expand_all() { 
	if ($('.expandable:first').is('.expanded')) {
		$('.expandable').removeClass('expanded');
	} else {
		$('.expandable').addClass('expanded');
	}
}

The headache with this snip­pet was my mis­un­der­stand­ing the jQuery.addClass and jQuery.removeClass pieces, orig­i­nally I had “.addClass(‘.expanded’)” and that add the class ‘..expanded’ — Oops.

I opted to use .is as opposed to the .has­Class sim­ply for it’s short length, no real rea­son here as both work by my understanding.