Currently Browsing: Home » JQuery Accordion Menu

JQuery Accordion Menu

In my previous jQuery post, I explained how to create a drop down menu. As I’ve stated before, there are many different types and styles of menus. For those of you wanting something different, here is an alternative menu.

This tutorial will take you through the creation of a jQuery accordion menu. There is a little twist to this: the menu contains content. Instead of it being links to multiple pages, it is a choice of what content should appear.

View a Demo Download the Files

Let’s start off with the HTML markup:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en-US">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>jQuery Accordion Menu</title> 

<style type="text/css">
* {
	margin: 0;
	padding: 0;
}

body {
	text-align: justify;
	font-size: 14px;
	line-height: 24px;
	font-family: "Trebuchet MS", Helvetica, Sans-Serif;
}

.accordian {
	width: 400px;
	margin: 50px auto;
}

.accordian li {
	list-style-type: none;
	padding: 0 5px;
}

.dimension {
	height: 400px;
}

.even, .odd {
	font-weight: bold;
	height: 27px;
	padding-top: 3px;
	padding-left: 10px;
}

.even {
	border: 1px solid #d8d8d8;
	background-color: #ececec;
}

.odd {
	border: 1px solid black;
	background: #333;
	color: white;
}
</style>

</head>
<body> 

<div class="accordian">
	<ul>
		<li>Quisque at erat vitae</li>
		<li>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec auctor, lorem et consectetur ultricies, nulla lacus iaculis odio, in laoreet lacus nisi vitae dolor. In commodo aliquet orci. Etiam pellentesque, sapien quis egestas gravida, velit dui tristique mi, at fringilla pede mauris id dolor. Integer bibendum ultrices enim. Integer tristique velit sollicitudin enim. Cras dapibus ullamcorper tellus. Suspendisse potenti. Nunc dolor mauris, tincidunt vitae, consectetur vel, feugiat vel, mauris. Nam purus nisi, volutpat in, lacinia eu, elementum id, lectus. Curabitur volutpat convallis tortor. Nulla eget neque. Donec id urna. Nulla ullamcorper tincidunt quam. Mauris quis enim. Praesent vulputate ipsum quis tortor. Nunc metus sem, malesuada nec, bibendum in, egestas eu, enim. Integer in purus. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae;</li>
		<li>Sed euismod massa</li>
		<li>Mauris bibendum justo sit amet lectus laoreet faucibus. Aliquam cursus, diam sed lacinia ultrices, urna ipsum auctor lacus, id vulputate ante ligula aliquam odio. Fusce feugiat risus at nisl. Sed cursus, tortor et iaculis viverra, augue quam interdum ligula, nec sollicitudin libero urna nec felis. Quisque rutrum, sapien ac euismod commodo, nibh metus ultrices erat, eu euismod mi magna non pede. Fusce magna velit, interdum ut, rutrum et, ultrices sed, risus. Praesent malesuada metus ut nibh. Suspendisse nec purus. Aenean est. Donec lectus. Pellentesque enim. Nulla tempus, ipsum sed placerat consectetur, nisl pede euismod sapien, in aliquam sapien erat a elit. Aliquam ac est. Etiam id dolor. In eget augue. Morbi varius sapien quis velit. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce a diam. Etiam pretium consectetur enim. Cras aliquam ipsum in augue.</li>
		<li>Proin et orci sit amet</li>
		<li>Sed vitae magna. Aliquam faucibus, felis ullamcorper feugiat semper, tortor leo tincidunt nibh, a faucibus lorem magna a nisi. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Sed sit amet mauris eget elit tincidunt hendrerit. Suspendisse vulputate, risus vitae sagittis blandit, arcu tortor venenatis nisl, vitae pharetra pede pede vulputate massa. Sed varius lectus a est. Nam vehicula. Pellentesque condimentum pellentesque pede. Praesent euismod felis quis augue. Morbi consequat eleifend tortor. Donec sed lorem. Cras facilisis, lacus a adipiscing interdum, augue elit feugiat odio, vel tempor justo sapien vitae tortor. Donec suscipit libero vel lectus. Vestibulum ipsum diam, laoreet nec, fringilla ac, vehicula nec, diam. Nulla tempus cursus dolor. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.</li>
	</ul>
</div>

<!-- Add jQuery From the Google AJAX Libraries -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script> 

<!-- Import The jQuery Script -->
<script type="text/javascript" src="jMenu.js"></script> 

</body>
</html>

This code sets up the accordion menu inside a divider.

Each even list element (remember that list elements are indexed starting from 0) is the title given to our content. For example, Quisque at erat vitae is the first title in our menu. Each odd list element is the content itself.

Note that there is also some inline CSS in this markup. Most of it very simple. There are a few irregularities:

  • The .dimension, .even, and .odd classes are never used directly in the HTML. These classes are applied by JavaScript.
  • Code inside the.dimension class should specify the height of each list element that contains content.
  • All even content titles may have separate styles from those that are odd. These go inside the .even and .odd classes.

The final task is to complete the JavaScript. This will go in its own file called jMenu.js.

First, we must hide all the content. Only the first list element with content should be visible:

$('.accordian li:odd:gt(0)').hide();

To make it easy for the reader to see what content he is viewing, we can add a slight padding to the corresponding title. In this case, we should add this to the first title:

$('.accordian li:first').animate( {
	paddingLeft:"30px"
} );

At this point, we should add the .dimension, .even, and .odd classes to our jQuery accordion menu through JavaScript:

$('.accordian li:odd').addClass('dimension');
$('.accordian li:even:even').addClass('even');
$('.accordian li:even:odd').addClass('odd');

We have to set the correct cursor for the title links:

$('.accordian li:even').css('cursor', 'pointer');

Now it’s time to handle the click event. When a title is clicked, we have to show the corresponding content. Because this is an accordion menu, it is also necessary to hide the content that was previously shown. Some animation may also be added for better effects:

$('.accordian li:even').click( function() {
	var cur = $(this).next();
	var old = $('.accordian li:odd:visible');

	if ( cur.is(':visible') )
		return false;

	old.slideToggle(500);
	cur.stop().slideToggle(500);

	$(this).stop().animate( {
		paddingLeft:"30px"
	} );

	old.prev().stop().animate( {
		paddingLeft:"10px"
	} );
} );

Here is the final JavaScript:

$(function() {
	$('.accordian li:odd:gt(0)').hide();
	$('.accordian li:first').animate( {
		paddingLeft:"30px"
	} );

	$('.accordian li:odd').addClass('dimension');
	$('.accordian li:even:even').addClass('even');
	$('.accordian li:even:odd').addClass('odd');

	$('.accordian li:even').css('cursor', 'pointer');

	$('.accordian li:even').click( function() {
		var cur = $(this).next();
		var old = $('.accordian li:odd:visible');

		if ( cur.is(':visible') )
			return false;

		old.slideToggle(500);
		cur.stop().slideToggle(500);

		$(this).stop().animate( {
			paddingLeft:"30px"
		} );

		old.prev().stop().animate( {
			paddingLeft:"10px"
		} );
	} );
});

Thanks for reading!

This entry was posted on Friday, February 20th, 2009 at 15:04:16. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

20 Responses to “JQuery Accordion Menu”

  1. Hi there…so…I have your script working as a test at (just started working on this project) http://suewaitelangley.com/DrC/templateinside.html

    That’s all good…

    But…

    I also want to use it on the blog page to go with this site. I use b2evo.

    I think that in order to get it to work where you have even/odd for titles and text…I would like the blog post title and content to appear.

    I think that with b2evo these items will need to be separate . It’s easy enough to make the into in the html code…but…not being a javascript expert can the javascript be modified to handle this change.

    Before I go all crazy trying to make it work…I thought I’d ask IF there was a possibility that it COULD work.

    Thanks so much for a nice script!

    Sue

  2. lance says:

    great tutorial –

    So I have a question. I’d have 6 toplevel items. in each of these sections, I have 2 or 3 subcategories. when I click on a subcategory (for instance in the 3rd section, it takes me to that url, however, it always opens up the first toplevel section. make sense?

    Is there a way to say — hey — im clicking in the 3rd level, so when you open this url — open the 3rd level area as well — and close all the others??

    I’m not a jquery pro — nor js — so any help would be great!

    thanks again!!!
    L

  3. MammaD says:

    Is it possible to put more than one menu on one page? I would like to use each menu to showcase a product and relevant information about it.

    Thanks.

  4. Hey there, great accordion! I’m wondering if these can be made dynamic… I’m using them on a travel site, and want a given accordion item to open up upon entering a certain section of the site. What would the command be to target dynamically? Thanks!

  5. sadhu says:

    hi, i wonder how can i style highlighted tab and rollover’s style?

  1. Some links for light reading - Part 1 | just4freaks.de
  2. 前端观察第六期 | 前端观察
  3. Css howto » JQuery Accordion Menu
  4. 10 great jQuery resources welcomebrand
  5. Accordion – Plugins, Demos and Tutorials - Hidden Pixels
  6. 12 Amazing jQuery Accordions Menus Collection | gazzan.sixserve.com
  7. 30 jQuery Accordion Menus, Tutorials And Best Examples
  8. 30 jQuery Accordion Menus, Tutorials And Best Examples | My Free Design Area - A Webpage for Joomla Free & Commercial Templates, Wordpress Free & Commerciak Themes, and Drupla Free and Commercial templates, Flash Templates and animation, Html temp
  9. 30 jQuery Accordion Menus, Tutorials And Best Examples | TechFleck
  10. 30 jQuery Accordion Menus, Tutorials And Best Examples « Websitetutorials’s Blog
  11. jQuery tuts en inglés | gorkaerrea.com | diseño bilbao
  12. 20 jQuery Accordion Container Choices and Examples. :MS-Joe (Joe Stagner)
  13. 10 great jQuery resources | welcomebrand

Leave a Reply

Want to be notified when someone replies? Subscribe to this post's comment RSS feed.
Any field marked with a * is required.