David Walsh Blog

Fancy FAQs with MooTools Sliders: Version 2

A little over a year ago I authored a post titled Fancy FAQs with MooTools Sliders. My post detailed a method of taking boring FAQs and making them more robust using the world’s best JavaScript framework: MooTools. I’ve taken some time to improve my original code for optimal performance and functionality.

The HTML



This is question 1

Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae....

This is question 2

Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae....

Our MooTools JavaScript will be reliant upon a simple HTML structure of H3s followed by DIVs.

The CSS


#faqs h3	{ cursor:pointer; }
#faqs h3.active	{ color:#d74646; }
#faqs div   {  }

You see I have very little CSS above — just the bare necessities. It’s up to you to make the content even more sexy. Maybe add some tweening on the content DIV when they show and hide.

The MooTools JavaScript


window.addEvent('domready',function() {
	$$('#faqs h3').each(function(header,i) {
		var state = false, answer = header.getNext('div');
		answer.slide('out');
		header.addEvent('click',function(e) {
			state = !state;
			answer.slide(state ? 'in' : 'out');
			if(state) {
				header.addClass('active');
			}
			else {
				header.removeClass('active');
			}
		});
	});
});

We start by grabbing all of the H3 tags within the designated parent element. We then:

  1. Cycle through each heading (the “question”)
  2. Grab the next DIV and consider it our “content” container (the “answer”)
  3. Slide the answer out of view
  4. Add a click event to the question which will toggle the display of the answer.

Another Take

The above code is accessible but sacrifices a clean effect during normal page load because you see a “flicker” of all of the answers displaying before JavaScript hides them. If accessibility is less of a concern and you want a smoother effect, consider adding the following CSS and JavaScript:


#faqs div	{ height:0; overflow:hidden; }

…and the JavaScript…


window.addEvent('domready',function() {
	$$('#faqs h3').each(function(header,i) {
		var state = false, answer = header.getNext('div');
		answer.slide('out');
		header.addEvent('click',function(e) {
			state = !state;
			answer.slide(state ? 'in' : 'out');
			header[(state ? 'add' : 'remove') + 'Class']('active');
		});
		answer.setStyles({
			overflow: '',
			height: 'auto'
		});
	});
});

This effect is much smoother.

So what do you think? Would you use this on a customer site?