Create a jQuery Accordion Menu

With just a few lines of jQuery and a little HTML/CSS you can have a nice, collapsible jQuery accordion menu that expands on click. Here is a quick example:

Create an unordered list with your listed nav items and give the first ul an id so we can target it later. I’ll call mine #sidenav.

<ul id="sidenav">
  <li><a href="#">Tier 1</a>
    <ul>
      <li><a href="#">Tier 2</a></li>
      <li><a href="#">Tier 2</a></li>
      <li><a href="#">Tier 2</a></li>
    </ul>
  </li>
  <li><a href="#">Tier 1</a>
    <ul>
      <li><a href="#">Tier 2</a></li>
      <li><a href="#">Tier 2</a></li>
    </ul>
  </li>
  <li><a href="#">Tier 1</a>
    <ul>
      <li><a href="#">Tier 2</a></li>
      <li><a href="#">Tier 2</a></li>
      <li><a href="#">Tier 2</a></li>
      <li><a href="#">Tier 2</a></li>
    </ul>
  </li>
  <li><a href="#">Tier 1</a>
    <ul>
      <li><a href="#">Tier 2</a></li>
      <li><a href="#">Tier 2</a></li>
      <li><a href="#">Tier 2</a></li>
    </ul>
  </li>
</ul>

Now you can add some styles to the menu via CSS. An important thing to note here is giving the sub menus a display:none;

#sidenav li a {
    display: block;
    padding: 10px 15px;
}
#sidenav li ul {
    display: none;
}
#sidenav li ul li a {
    padding: 10px 25px;
}

And now just a bit of jQuery to create the accordian. By adding a new class (active), you can see if there is a sub menu already open when a link is clicked – You can also use that class to style the opened menu.

$(document).ready(function () {
  $('#sidenav > li > a').click(function(){
    if ($(this).attr('class') != 'active'){
      $('#sidenav li ul').slideUp();
      $(this).next().slideToggle();
      $('#sidenav li a').removeClass('active');
      $(this).addClass('active');
    }
  });
});

One comment

Leave a Reply

Your email address will not be published. Required fields are marked *