Wednesday, 27 February 2013

Fancy FAQs with jQuery Sliders

The HTML > This is question 1? > > This is the answer to question #1. Pellentesque habitant morbi.... > This is question 2? ... thumbnail 1 summary

The HTML


>This is question 1?




>

>This is the answer to question #1. Pellentesque habitant morbi....





>This is question 2?




>

>This is the answer to question #2. Pellentesque habitant morbi....




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; }
Some CSS properties may need to be vendor-prefixed.
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; }
Some CSS properties may need to be vendor-prefixed.
$(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!

No comments

Post a Comment