a simple accordion menu with jquery
Apr
20
1
0
I've seen a lot of bloated scripts trying to attach an accordion effect onto a nested menu that just end up being slow, buggy, complicated, and hard to extend. I think people are over thinking things . If you're using JQuery it's easy enough to write this functionality yourself.
Lets say your HTML looks something like this:
<ul id="accordion">
<li>
<h1>First</h1>
<ul>
<li><a href="#">section</a></li>
<li><a href="#">section</a></li>
<li><a href="#">section</a></li>
</ul>
</li>
<li>
<h1>Second</h1>
<ul>
<li><a href="#">section</a></li>
<li><a href="#">section</a></li>
<li><a href="#">section</a></li>
</ul>
</li>
<li>
<h1>Third</h1>
<ul>
<li><a href="#">section</a></li>
<li><a href="#">section</a></li>
<li><a href="#">section</a></li>
</ul>
</li>
</ul>You can easily initialise and attach the accordion functions like so:
$(document).ready(function() {
// initialise
$('ul#accordion > li > ul').hide();
$('ul#accordion > li:first-child > ul').show();
// accordion
$('ul#accordion > li > h1').click(function() {
// do nothing if already expanded
if($(this).next().css('display') == 'none') {
$('ul#accordion > li > ul').slideUp();
$(this).next().slideDown();
}
});
});I hope you find this code simple and easy to extend.
