Back to Blog

Simple Accordion with JavaScript and jQuery

Author

Jump right in and check out the example

I’ve explored many of the accordion jQuery plugins out there, and they all seem to be overkill and overly complex. I guess if you want something to work the way you imagine you need to build it yourself. Here’s a really, really simple way to build a sliding accordion with just 12 lines of JavaScript and jQuery. First, we’ll start with the XHTML structure I’ve used.

  • Reliability Engineering Consulting (366)

    • Vibration Analyst (117)
    • Oil/Tribology/Lubrication Engineer (93)
    • Non-Destructive Testing (81)
    • Motor Circuit (75)
  • Reliability Engineering Consulting (366)

    • Vibration Analyst (117)
    • Oil/Tribology/Lubrication Engineer (93)
    • Non-Destructive Testing (81)
    • Motor Circuit (75)
  • Reliability Engineering Consulting (366)

    • Vibration Analyst (117)
    • Oil/Tribology/Lubrication Engineer (93)
    • Non-Destructive Testing (81)
    • Motor Circuit (75)

In my example I’ve added some basic icons and css to give it some clarity for usability purposes. Here’s the CSS I’ve used, this can be modified to make things work for you.

ul.expand { padding:0; margin:0; list-style:none; }
ul.expand li { padding:0; margin:0; }
ul.expand li.trigger.top { margin-top:0; }
ul.expand li.trigger
{
	background:url(expand-collapse.gif) 0 3px no-repeat;
	cursor:pointer;
	padding:0 0 0 20px;
	margin:7px 0 0 0;
}
ul.expand li.trigger h4
{
	color:#666;
}
ul.expand li.trigger.open h4
{
	color:inherit;
}
ul.expand li.trigger.open
{
	background-position:0 -997px;
}
ul.expand ul
{
	list-style:disc inside;
	line-height:18px;
	padding:4px 0 6px 20px;
}

Next we need to add the JavaScript to make it all work. Before we can do this you MUST include a copy of the jQuery JavaScript library or this WILL NOT WORK. Once you have that done, add the following after you’ve linked to jQuery.

$(function(){
		$('ul.expand').each(function(){
		$('li.trigger', this).filter(':first').addClass('top').end().filter(':not(.open)').next().hide();
		$('li.trigger', this).click(function(){
			if($(this).hasClass('open')) {
				return false;
			} else {
				$(this).parent().find('li.trigger').removeClass('open').next().filter(':visible').slideUp();
				$(this).addClass('open').next().slideDown();
			}
		});
	});
});

That’s it, your ready to go. If you add a class of open onto one of the triggers it will be open by default. If anyone needs an explanation on how this works I can do a write up, everything should be pretty straight forward in the CSS in terms of design.

Check out the example

Author

How we work Process

Product Hero Talin Wadsworth