Drop us a line 0116 403 0288

jQuery FAQ

Whilst re-developing a client’s website this week we decided to spruce up the FAQ page using jQuery, whereby you click on a question to reveal the answer. However, before we started we set ourselves a couple of requirements:

  1. We wanted our new list of questions and answers to be presented via a definition list. This felt like the most semantic way of doing it.

  2. We wanted the list of questions and answers to still be accessible if JavaScript isn’t available, so the “click to reveal” functionality is merely progressive enhancement.

Here’s how we did it:

The HTML

<dl class="faq">
    <dt>What are your opening hours?</dt>
    <dd><p>We're open from 9am until 5pm, Monday to Friday</p></dd>
    <dt>How long have you been established?</dt>
    <dd><p>We've been established since 1999</p></dd>
</dl>

The CSS

This part’s up to you. Style your definition list however you like.

The jQuery

$(function() {
	$("dl.faq").each(function() {
	    var dl = $(this);
	    dl.children("dt").css("cursor", "pointer").on("click", function() {
	        $(this).toggleClass("active").next("dd").slideToggle();
	    }).next("dd").hide();
	});
});

You’ll notice that the cursor is applied to the definition title inline by the jQuery script rather than in the CSS. This is because if JavaScript is disabled we don’t want the definition title to have the pointer cursor.

When the definition title is clicked on, the “active” class is appended to it. This allows you to style the definition title differently when it’s clicked on, for example you could make it bold or change the colour.