David Walsh Blog

Fancy FAQs with jQuery Sliders

Frequently asked questions can be super boring, right? They don’t have to be! I’ve already shown you how to create fancy FAQs with MooTools — here’s how to create the same effect using jQuery.

The HTML


<h3>This is question 1?</h3>
<div>
	<p>This is the answer to question #1.  Pellentesque habitant morbi....</p>
</div>
<h3>This is question 2?</h3>
<div>
	<p>This is the answer to question #2.  Pellentesque habitant morbi....</p>
</div>
<!-- more... -->

Simply a series of H3s and DIVs wrapper in one container DIV. Simple, simple, simple.

The CSS


#faqs { position:relative; }
#faqs h3	{ cursor:pointer; }
#faqs h3.active	{ color:#d74646; }
#faqs div   { position:relative; }
#faqs div p	{ padding:0; margin-bottom:15px; }

Nothing out of the ordinary above — format the elements as though there wont be a jQuery component.

The jQuery JavaScript


$(document).ready(function() {
	$('#faqs h3').each(function() {
		var tis = $(this), state = false, answer = tis.next('div').slideUp();
		tis.click(function() {
			state = !state;
			answer.slideToggle(state);
			tis.toggleClass('active',state);
		});
	});
});

Start by collecting and recursing through all of the H3 elements. Grab the DIV that follows, slide it in, and add click handlers to slide them in and out!

A More Elegant Effect

The above method is the more accessible version. If effects are you priority, the following CSS and jQuery JavaScript variants will make for a more elegant effect by preventing the initial slide in:


#faqs h3	{ cursor:pointer; }
#faqs h3.active	{ color:#d74646; }
#faqs div { height:0; overflow:hidden; position:relative; }
#faqs div p	{ padding:0; margin-bottom:15px; }

$(document).ready(function() {
	$('#faqs h3').each(function() {
		var tis = $(this), state = false, answer = tis.next('div').hide().css('height','auto').slideUp();
		tis.click(function() {
			state = !state;
			answer.slideToggle(state);
			tis.toggleClass('active',state);
		});
	});
});

There you have it. Have fun with your FAQs!