REALLY Simple jQuery Accordion

I get asked how to make a Javascript accordion all the time, and there are a lot of great framework plugins and code snippets around, but most of the time the features that these plugins include just aren’t needed. So, here is just about the most basic Javascript accordion you could make, using just a few lines of jQuery and plain old HTML/CSS. It will degrade when Javascript isn’t available, and the example validates to XHTML 1.1 (as I hope it would, with so little code). The jQuery goes a little like this:

  1. $(function() {
  2.     $(‘.accordion .items’).hide();
  3.     $(‘.accordion .heading’).mouseover(function() {
  4.             $(this).
  5.                 next(‘.items’).
  6.                 slideDown(‘fast’).
  7.                 siblings(‘.items’).
  8.                 slideUp(‘fast’);
  9.     });
  10. });

Of course, I don’t recommend you just use this example verbatim – apart from the fact that it looks horrible, there are usability issues surrounding doing the accordion effect straight up like this. For a start, I’d recommend looking into the great hoverIntent jQuery plugin so things don’t get crazy on your users.

The example is below, and you can grab the code here: Simple jQuery Accordion Example.

  • http://play.blog2t.net Og2t

    Fantastic, I personally fall for accordions, your one is the shortest I’ve even seen :)

  • Drizzy

    is it possible for it to collapse more into sub heading as well?

    So basically if you had a heading:

    i.e.

    > Major Attractions ‘you click that it drops down to’
    > CN Tower ‘and when you click that it drops down
    > ‘a short description of the CN tower’

    is something like that possible ?

  • http://bradkellett.com Brad Kellett

    Yeah, absolutely. It's basically just a copy-paste of the block of code but substituting for the second level item class names.

  • Drizzy

    I don't understand can you put an example of code
    thanks in advance

  • Drizzy

    I'm using this code though….

    <script type=”text/javascript”>
    $(document).ready(function($) {
    $('#accordion dd').hide();
    $('#accordion dt a').click(function(){
    $('#accordion dd').slideUp();
    $(this).parent().next().slideDown();
    return false;
    });
    });
    </script>