Tight & Tiny jQuery Horizontal Accordion

Yesterday I decided I would get MooTools off my site once and for all. No offense to any of y’all who are still fans, I’m just a bigger fan of jQuery now. After a few minutes of Googling for a “jquery horizontal accordion” and finding most to be too heavy, unwieldy or have too many requirements, I decided to make my own, and make it really small.

We really only need two types HTML elements: links to toggle the content, and the content panes themselves. However, I’m also using a wrapper to center the accordion on the page, and a nested content element to smooth transitions. That nesting will prevent the text from being squished and wrapping repeatedly on every expansion and contraction. But four style declarations won’t be so bad, now will it?

So once we have that framework let’s start with the script:

$(document).ready(function() {
	$('.accordionLink').click(function() {

// If the pane is already expanded, close it:
		if($(this).hasClass('on')) {

// The .on class lets us style the active state as well:
			$(this).removeClass('on');

// The animate() method is all we need!
			$(this).next().animate({width: '0px'});
		 } 

// Not already expanded? Open it:
		else {

// Any other panes which are open get closed:
			$('.accordionLink').removeClass('on');
			$('.accordionFrame').animate({width: '0px'});

// Then activate the one you clicked:
			$(this).addClass('on');
			$(this).next().animate({width: '167px'});
		}
	 });
});

And now the CSS. Note that the wrapper has a set width and auto margin for centering, the links and content frames also have set initial dimensions, and the link has hover and active psuedoclasses as well as “on” class styles:

#accordionWrapper {
	width: 755px;
	height: 300px;
	margin: 0 auto;
}
#accordionWrapper .accordionLink {	
	width: 167px;
	height: 300px;
	float: left;
	cursor: pointer;
	background: #000033;
	color: #fff;
}
#accordionWrapper .accordionLink:hover { background: #006; }
	
#accordionWrapper .accordionLink:active,
#accordionWrapper  .accordionLink.on {	
	background: red;
	color: #000;
}
#accordionWrapper .accordionFrame {	
	display: block;
	width: 0px;
	height: 300px;
	float: left;
	overflow: hidden;
	border-right: 1px solid #666;
	background: #ccc;
}
#accordionWrapper .accordionFrame .content {
	width: 147px;
	padding: 0px 10px;
}

And that’s it! Now you’ve got a tiny horizontal accordion that works basically everywhere, including XP IE7, for those of you whose clients are still doing business on a Compaq.

Check out the live example

Just copy from above, save or view-source the example to grab it and make your accordions a lot tighter. Enjoy!

1 comment

Leave a comment

Your email address will not be published. Required fields are marked *