jQuery Simple FAQ

Simple FAQ: This example uses jQuery to build a simple show/hide FAQ with feedback. Clicking the headings reveals the linked text. Clicking another heading hides all the others and shows the clicked one.

A Simple jQuery FAQ

I've heard that JavaScript is the long-lost fountain of youth. Is this true?

Why, yes it is! Studies prove that learning JavaScript freshens the mind and extends life span by several hundred years. (Note: some scientists disagree with these claims.)

Can JavaScript really solve all of my problems?

Why, yes it can! It's the most versatile programming language ever created and is trained to provide financial management advice, life-saving CPR, and even to take care of household pets.

Is there nothing JavaScript can’t do?

Why, no there isn’t! It’s even able to write its own public relations-oriented Frequently Asked Questions pages. Now that’s one smart programming language!

Notes:


See the code:


<script>
$(document).ready(function(){
  
  // Hides all the answers when page is first loaded
  $('.answer').hide();
  			
  $('.main h2').click(function() {
    // Hides *all* the answers
    $('.answer').hide();
				
    // User Feedback: Removes the "close" class from all FAQ headings
    // This removes the "-" sign which indicates the currently displayed element 
    $('.main h2').removeClass('close');
				
    // User Feedback: Add the "close" class to the currently shown element
    // This is positioned above the "show answer" function as there was a delay in
    // displaying the feedback if it is done after. This makes the FAQ seem more responsive.
    $(this).addClass('close');
				
    // Shows just the answer associated with the currently clicked heading
    // .toggle() switches between hiding and showing an element. Since
    // all answers are hidden now, it uses $this and .next to just show
    // the answer associated with the clicked heading.
    // V1.1 - changed .toggle() to .fadeIn() to animate showing text.
    $(this).next('.answer').fadeIn("slow");
  }); // end Toggle
}); // end ready
</script>