Simple jQuery Accordion

I was looking for a super simple accordion plug in that had the following attributes:

  • Had simple HTML markup
  • Did not require a big, extensive stylesheet and images
  • Could be created simply by markup
Didn’t find it right away so I created one myself. It is really simple, but it does everything I needed it to do. Feel free to use this as is or as a starting point. Released under the MIT license.The plug in will treat every odd child of your accordion element as a “handle” and every even one as a “drawer”. When handles are clicked the drawer is toggled open or shut. If you want a drawer to default as open, set its class to “open”.

The HTML

<div id="accordion1">
  <a href="#">Heading</a>
  <div class="open">Contents</div>
  <a href="#">Heading 2</a>
  <div>Contents</div>
  <a href="#">Heading 3</a>
  <div>Contents</div>
</div>

Then the Javascript:

$("#accordion1").accordion();

The Plugin Code

(function ($) {
    $.fn.accordion = function (method) {
        var methods = {
            init: function (options) {
                if (options == null) options = {};
                this.each(function () {
                    var $this = $(this);
                    if ($this.hasClass("initialized")) return $this;
                    $this.addClass("accordion initialized");
                    var index = 0;
                    $this.children().each(function () {
                        var $child = $(this);
                        if (index % 2 == 0) {
                            $child.addClass("handle").bind("click", function () {
                                $child.toggleClass("open").next(".drawer").toggleClass("open").slideToggle();
                                return false;
                            });
                        }
                        else {
                            $child.addClass("drawer");
                            if ($child.hasClass("open"))
                                $child.prev(".handle").addClass("open");
                            else
                                $child.css({ display: "none" });


                        }
                        index++;
                    });
                });
                return $(this);
            }
        }
        if (methods[method])
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        else if (typeof method === 'object' || !method)
            return methods["init"].apply(this, arguments);
        else
            $.error("Method " + method + " does not exist");
    }
})(jQuery);

For the latest version and a sample, visit the repository on github.

So, what do you think ?