Alessandro Dotti Contra

Linux/Unix DevOps


JQuery accordion menu

Accordion menu are a nice way to add some kind of _motion_ to a website. This is the basic implementation of an accordion menu, without effects or other fancy stuff.

HTML markup

The HTML markup is pretty simple. We just have to define the hyerarchical structure of the menu using some lists, and add all the relevant classes that will be used later by the javascript code and the style sheet.

<div id="accordion">
<ul>
	<li class="menu">
		<div class="button">
			<a class="accordion" href="#">Section one</a>
    	</div>
		<ul class="options">
			<li>
	            <a class="option" href="#">topic one</a>
            </li>
            <li>
                <a class="option" href="#">topic two</a>
            </li>
            <li>
                <a class="option" href="#">topic three</a>
            </li>
        </ul>
    </li>
    <li class="menu">
        <div class="button">
	        <a class="accordion" href="#">Section two</a>
        </div>
        <ul class="options">
            <li>
                <a class="option" href="#">topic one</a>
            </li>
        </ul>
    </li>
    <li class="menu">
        <div class="button">
			<a class="accordion" href="#">Section three</a>
        </div>
        <ul class="options">
            <li>
                <a class="option" href="#">topic one</a>
            </li>
            <li>
                <a class="option" href="#">topic two</a>
            </li>
        </ul>
    </li>
</ul>
</div>

Code snippet

The trick is to add or remove the relevant classes to the elements we want to show or hide.

$(function(){
	//Collapse accordion
	$('.options').hide();
	//When button is clicked...
	$('a.accordion').click(function() {
		//Check which set of options to show
		var button	= $(this).parent();
		var options = $(this).parent().siblings('ul');
		//If this set of options is active...
		if(button.hasClass('active')) {
			//Clear the active flag
			button.removeClass('active');
		} else {
			//Hide the set of options currently shown
			var current = $('.button.active');
			var shown = $('.button.active').siblings('ul');
			current.removeClass('active');
			shown.toggle();
			//Mark this set of options as active
			button.addClass('active');
		}
		//Toggle the set of options
		options.toggle();
	});
});

CSS snippet

And here is a touch of style.

#accordion ul {
	list-style: none;
	padding: 0;
	margin: 0;
}
#accordion li {
	list-style: none;
	margin: 1px 0;
}
#accordion a.accordion {
	background-color: #FFFFFF;
	color: #27ADD7
}
#accordion a.option {
	background-color: #FFFFFF;
	color: #27ADD7
}
#accordion .button {
	border: solid 1px #27ADD7;
	height: 30px;
	width: 150px;
	padding: 15px 0 0 30px;
	background-color: #FFFFFF;
	color: #000000;
}
#accordion .options {
	padding: 15px 0 15px 25px;
}
View demo