Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery Accordion Close then Open

I've set up a number of accordions on a page using the jquery accordion plugin so I can implement expand all and collapse all functionality.

Each ID element is it's own accordion and the code below works to close them all no matter which ones are already open:

$("#contact, #address, #email, #sales, #equipment, #notes, #marketingdata")
    .accordion("activate", -1)
;

My problem is with the expand all. When I have them all expand with this code:

$("#contact, #address, #email, #sales, #equipment, #notes, #marketingdata")
    .accordion("activate", 0)
;

Some will contract and some will expand based on whether or not they are previously open.

My idea to correct this was to collapse them all and then expand them all when the expand all was clicked. This code however won't execute properly:

$("#contact, #address, #email, #sales, #equipment, #notes, #marketingdata")
    .accordion("activate", -1)
;
$("#contact, #address, #email, #sales, #equipment, #notes, #marketingdata")
    .accordion("activate", 0)
; 

It will only hit the second command and not close them all first. Any suggestions?

like image 621
Jon Avatar asked Dec 19 '08 21:12

Jon


1 Answers

I'm not exactly sure what you're after, but this is my best guess. Out of all your accordions, you want the "open all" button to open all the accordions which are closed (that is, no section is showing). I'd do that by using filter()

$("#contact, #address, #email, #sales, #equipment, #notes, #marketingdata")
    .filter(":not(:has(.selected))")
    .accordion("activate", 0)
;

Is that what you were after?


Edit to explain that filter function:

The filter function just runs your current selection through a filter, removing anything which doesn't match. It has two different forms: one where you pass a regular jQuery query in, like i did above, and the other where you can define a function to filter. If the function returns false, then that element is removed.

In this case the query removes anything which doesn't (:not) have (:has) a child with class "selected" (.selected). I used the .selected selector here because that's what the accordion adds to the currently-open panel.

If you only had one accordion, or you gave each of your accordions some sort of identifier, such as a class name, then you could greatly reduce the entire script. Let's say that for each element you want to turn into an accordion, you give it the class "accord".

$(".accord:not(:has(.selected))").accordion("activate", 0);

This is much more legible and maintainable, since you can easily add more accordions in the future if you wish and this will handle it.

The documentation for filter is here: http://docs.jquery.com/Traversing/filter

like image 161
nickf Avatar answered Nov 07 '22 04:11

nickf