Making an Accordion Using jQuery


It’s easy to make an accordion using plain vanilla jQuery.  If you don’t use jQuery UI or would like to use only jQuery then the following code will create the accordion behavior. The accordion demo illustrates what we are building.
Given the html markup structure below how would you create an accordion behavior?
Accordion Header 1
  • Machine Gun
  • Knife
  • Machete
Accordion Header 2
  • Ninja
  • Robot
  • Samurai


You can give the preceding html an accordion behavior with the following javascript. The trick
is using the not() method that jQuery provides to easily select the other elements.
    $(function() {  
        $('.accordian .head').click(function() {

            $('.accordian .head').not(this).removeClass('ui-highlight')
                                 .next().slideUp();
            $(this).toggleClass('ui-highlight').next().slideToggle();

        }).next().hide();
    });
See the accordion demo