jQuery Expand All

Here’s another lunchtime jQuery snippet as the last one proved semi-popular. This one came about today as I needed to expand on an existing expand/collapse functionality to allow users to expand or collapse all of the objects with this functionality.

What had already been done was set a jQuery function to react on the presence of the .expanded class. The way it works is very simple, jQuery grabs all the elements with the .expandable class and then using the :first selector it tests the first one to see whether it is expanded or not. Then depending on the outcome 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 snippet was my misunderstanding the jQuery.addClass and jQuery.removeClass pieces, originally I had “.addClass(‘.expanded’)” and that add the class ‘..expanded’ — Oops.

I opted to use .is as opposed to the .hasClass simply for it’s short length, no real reason here as both work by my understanding.

2 thoughts on “jQuery Expand All”

  1. Hey thanks for the awesome code snippet. This might be a long shot because you originally posted this several years ago, but I’m wondering if you could show and example of this in action. I’m trying to integrate your toggle_expand_all code with this fella’s code (http://henrik.nyh.se/2008/02/jquery-html-truncate). If you do happen to get around to responding to my question, fyi I’m new to jquery and still padding around on hands and knees trying to make the most of it. Oh, and here’s the page I’m trying to implement this on: http://sfplanning.org/index.aspx?page=2754 Thanks! Monica

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>