Lupine Software Development

Customizable Generic jQuery Accordion

by LupineDev

Here is a pretty simple way to quickly make a simple but completely CSS customizable accordion using jquery and a cleverly set up unordered list.

Lets start with the html:

<ul class="acc_ul">
  <li>
    <h5 class="collapsed">Eddard Stark</h5>
    <h5 class="expanded">Eddard Stark</h5>
    <div class="acc_content">
      Lorem ipsum dolor sit amet...
    </div>
  </li>
  <li>
    <h5 class="collapsed">Tyrion Lannister</h5>
    <h5 class="expanded">Tyrion Lannister</h5>
    <div class="acc_content">
      Curabitur aliquet auctor posuere...
    </div>
  </li>
  <li>
    <h5 class="collapsed">Samwell Tarly</h5>
    <h5 class="expanded">Samwell Tarly</h5>
    <div class="acc_content">
      Nam lectus nisi, tempus et sagittis quis...
    </div>
  </li>
  <li>
    <h5 class="collapsed">Theon Greyjoy</h5>
    <h5 class="expanded">Theon Greyjoy</h5>
    <div class="acc_content">
      Nulla facilisi. Nunc in nibh sit amet ante...
    </div>
  </li>
  <li>
    <h5 class="collapsed">Jaime Lannister</h5>
    <h5 class="expanded">Jaime Lannister</h5>
    <div class="acc_content">
      Aenean magna nulla, tincidunt non vehicula eu...
    </div>
  </li>
</ul>

Now a little CSS:

<style type="text/css" rel="stylesheet">
  ul.acc_ul {
    border-top: 1px solid #333333;
    margin: 0px;
    padding: 0px;
  }
  ul.acc_ul li {
    border-bottom: 1px solid #333333;
    list-style: none;
    margin: 0px;
    padding: 0px;
  } 
  ul.acc_ul li h5 {
    font-size: 14px;
    margin: 0px;
    padding: 12px;
  }
  ul.acc_ul li h5:hover {
    background-color: #333333;
  }
  div.acc_content {
    padding: 0 12px 12px 12px;
    font-size: 12px;
  }
</style>

Finally the jQuery javascript:

<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script type="text/javascript">
  $(document).ready(function(){
    // first hide the collapsed headers and accordion content
    $('ul.acc_ul li h5.expanded').hide();
    $('ul.acc_ul li div.acc_content').hide();

    // now setup action when h5 is clicked to expand
    $('ul.acc_ul li h5.collapsed').click(function(){
      // toggle h5s
      $(this).hide();
      $(this).siblings('h5.expanded').show();
      $(this).siblings('div.acc_content').slideDown(500);
    });

    // now setup action when h5 is clicked to close
    $('ul.acc_ul li h5.expanded').click(function(){
      // toggle h5s
      $(this).hide();
      $(this).siblings('h5.collapsed').show();
      $(this).siblings('div.acc_content').slideUp(500);
    });
  });
</script>

The nice thing about this is you can customize the CSS to fit perfectly with the rest of the site. The jQuery-UI library is awesome and way more powerful than this but sometimes it just doesn't completely mesh with the the theme you are trying to convey. That's where this can be useful, here's the full example...