Wednesday, September 5, 2012

Expanding multiple sections of a JQuery Accordion

I've loved using jQuery and jQuery UI on my current project.  They work, on all browsers, and they make things simple.  They are powerful and extensible - great tools. However, one thing that has really annoyed me is the jQuery UI accordion.  They have this snippet in their documentation:

NOTE: If you want multiple sections open at once, don't use an accordion

This drives me nuts!  If you have to write a note about something that the control doesn't do, bolded and in a larger font size in the documentation, because lots of people want to do that, or are asking for it, the control should probably perform that function.

This is exactly what I wanted to try out for one of our UI prototypes.  Usually, we wanted one section open at a time (the accordion behavior), but sometimes we want to see all 5 sections (say for printing or so you don't have to remember the first section when looking at the last section.

I found this excellent example of how to hack the jQuery UI accordion to allow multiple sections to be expanded at the same time: http://jsbin.com/eqape.

I then added this bit of JavaScript to expand and collapse all the sections.  These are hooked up as click handlers for a couple of icons on the page.


Expand/Collapse All
function accordion_expand_all()
{
  var sections = $('.accordion').find("h3");
  sections.each(function(index, section){
    if ($(section).hasClass('ui-state-default')) {
      $(section).click();
    }
  });
}

function accordion_collapse_all()
{
  var sections = $('.accordion').find("h3");
  sections.each(function(index, section){
    if ($(section).hasClass('ui-state-active')) {
      $(section).click();
    }
  });
}

This improved the jQuery accordion significantly and I hope we see all this behavior native to the control sometime in the future.

2 comments:

  1. Hey John, I tired to follow your direction and for some reason only the last accordion expand or collapse. In your example above I had to change .accordion to #accordion since Jqury ui uses an id and not a class. IS there anyway you could help?

    ReplyDelete
  2. It looks like the jquery UI interface / behavior has changed with the newer versions.

    ReplyDelete