jQuery Accordion

A tutorial to show how you can make a simple accordion using some CSS and jQuery


Code Library »

The Finished Project

How It's Done

First, a little bit of CSS

Just to make things look good on the page.

CSS Section

         a,a:hover,a:link,a:visited {
            color: #ffffff;
            text-decoration: none;
         }
         img {
            display: block;
            width: 100% !important;
            max-width: 100%;
            height: auto;
            vertical-align: middle;
         }
         #panel-wrapper {
            width: 640px;
            margin: 0 auto;
            padding-bottom: 50px;
         }
         dl.panel {
            border-bottom: 1px solid #886D31;
            margin: 0;
         }
         dl.panel:last-of-type: {
            border-bottom: none;
         }
         dl.panel > dt {
            background-color: #c8ac68;
            color: #ffffff;
         }
         dl.panel > dt > a {
            display: block;
            text-align: center;
            padding: 10px 0;
         }
         dl.panel > dd {
            margin: 0;
         }
            

Now for the interactive part, JavaScript.

JavaScript Section

      <script>      
         jQuery(document).ready(function($) {

            // Hide the panel boxes
            var panel = $('dl.panel > dd').hide();

            // Show the first panel (optional)
            panel.first().show();

            $('dl.panel > dt > a').click(function() {

               var $this = $(this);

               // Slide all panels up (close position)
               panel.slideUp();

               // Open panel that was clicked (open position)
               $this.parent().next().slideDown();

               // Don't allow link to go anywhere
               return false;

            });

         });      
      </script>