Build a FAQ toggler using jQuery 

Though I’m not expert at it, I love having a play with jQuery. I came up with this show-hide toggle script, useful for enhancing the presentation and usability of a ‘Frequently Asked Questions’ section on a website.

Unlike other scripts, this one allows the user to show individual answers or all answers on a FAQ.

Remember, the webpage will need to reference the jQuery library for this script to work.

HTML

Use a definition list (dl) to markup the FAQ.

<dl class="faqs">
	<dt>Question 1</dt>
	<dd>Answer 1</dd>
	<dt>Question 2</dt>
	<dd>Answer 2</dd>
	<dt>Question 3</dt>
	<dd>Answer 3</dd>
</dl>

<p><a id="show-hide-all">Show all</a></p>

 

jQuery

Clicking a question (dt) on the .faqs (dl) will show/hide the answer (dd) and will toggle the show-hide-all link between ‘Show all’ (if any items are hidden) and ‘Hide all’ (if all items are visible).

Clicking show-hide-all will show/hide all .faqs answers (dd) and will toggle the show-hide-all link text between ‘Show all’ (when all items are hidden) and ‘Hide all’ (when all items are visible).

(function($) {
	$(function() {

	$('.faqs dd').hide();
	$('.faqs dt').click(function () {
		$(this).next('.faqs dd').slideToggle(500);
			if ( $('.faqs dd:hidden').length == 0 ) {
				if ($('#show-hide-all').text()=='Hide all') 
					$('#show-hide-all').text('Show all');
				else 
					$('#show-hide-all').text('Hide all');
			}
			else $('#show-hide-all').text('Show all');
	});

	$('#show-hide-all').click(function () {
		if($('.faqs dd').is(':hidden')) {
			$('.faqs dd:hidden').slideToggle(500);
				if ($('#show-hide-all').text()=='Hide all') 
					$('#show-hide-all').text('Show all');
				else 
					$('#show-hide-all').text('Hide all');
			}
		else if ($('.faqs dd').is(':visible')) {
			$('.faqs dd:visible').slideToggle(500);
			$('#show-hide-all').text('Show all');
		}
	});

	});
})(jQuery);