How do I make a simple accordian menu?

September 26, 2011

HTML:


This is a typical nested list format. The list components that have an unordered child list group inside them need the following.
1) A link with a specified ID
2) A child ul list that has a class equal to the id of the link (from #1)

CSS:

ul{background:#faf7f3; margin:0; padding:0;}
li{display:block;  list-style-type:none; }
li a{ display:block; font-weight:bold; height: 20px; padding: 8px 0 8px 12px;}
li ul{margin: 8px 0 8px 0; padding:0;}
li ul li{display:block; list-style-type:none; font-weight:normal }
li ul li a{ font-weight:normal; padding: 1px 0 1px 12px; }

Just some styling to align the list items and make them look decent.

jQuery:

[script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"][/script]
[script type="text/javascript"]
$(document).ready(function() {
	$('ul#accordion a.heading').click(function() {
		$(this).css('outline','none');
		if($(this).parent().hasClass('current')) {
			$(this).siblings('ul').slideUp('slow',function() {
				$(this).parent().removeClass('current');
			});
		} else {
			$('ul#accordion li.current ul').slideUp('slow',function() {
				$(this).parent().removeClass('current');
			});
			$(this).siblings('ul').slideToggle('slow',function() {
				$(this).parent().toggleClass('current');
			});
		}
		return false;
	});
});
[/script]

Finally the code that makes the toggled list work.

————————–

NOTE: TOGGLE INITIAL SUB-NAVIGATION
You can set one of the toggle contents to be open by checking the URL and use the jquery toggle function on the sublist ID you want visible. The way I did it was to use the ‘indexOf’ function to see if the link contained a certain value. The following code would go after the click function in ‘$(document).ready’:

var loc = window.location.pathname
var pageVar = '#nothing';
if ((loc.indexOf("locate") != -1)||(loc.indexOf("job") != -1)||(loc.indexOf("timesheet") != -1)){
	pageVar = '#solutionsList'}
else if (loc.indexOf("support") != -1){
	pageVar = '#techSupport'}
	
$.fx.off = true;
$(pageVar).slideToggle('800',function() {
	$(pageVar).parent().toggleClass('current');
});
$.fx.off = false;

Stay in Touch!

Subscribe to our newsletter.

Solutions Architecture

browse through our blog articles

Blog Archive