jQuery Expand All

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.

Discussion

  1. Dave says:

    Very nice, that’s exactly what I needed to do :)

  2. Monica says:

    Hey thanks for the awe­some code snip­pet. This might be a long shot because you orig­i­nally posted this sev­eral years ago, but I’m won­der­ing if you could show and exam­ple of this in action. I’m try­ing to inte­grate your toggle_expand_all code with this fella’s code (http://henrik.nyh.se/2008/02/jquery-html-truncate). If you do hap­pen to get around to respond­ing to my ques­tion, fyi I’m new to jquery and still padding around on hands and knees try­ing to make the most of it. Oh, and here’s the page I’m try­ing to imple­ment this on: http://sfplanning.org/index.aspx?page=2754 Thanks! Monica

Add a Comment

*

* Copy this password:

* Type or paste password here:

*