Creating An Accordion Style FAQ System with jQuery and CSS3

Creating An Accordion Style FAQ System with jQuery and CSS3
File Size: 2.01 KB
Views Total:
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   

A basic animated FAQ system that allows you to expand and collapse answer panels by clicking the questions, built on top of CSS3 transitions & transforms and a little jQuery script.

How to use it:

1. Create a list of questions & answers for the FAQ system.

<div class="faq-header">Frequently Asked Questions</div>
<div class="faq-c">
  <div class="faq-q"><span class="faq-t">+</span>How do I select an item using class or ID?</div>
  <div class="faq-a">
    <p>This code selects an element with an ID of "myDivId". Since IDs are unique, this expression always selects either zero or one elements depending upon whether or not an element with the specified ID exists.</p>
  </div>
</div>
<div class="faq-c">
  <div class="faq-q"><span class="faq-t">+</span>How do I select elements when I already have a DOM element?</div>
  <div class="faq-a">
    <p>If you have a variable containing a DOM element, and want to select elements related to that DOM element, simply wrap it in a jQuery object.</p>
  </div>
</div>
<div class="faq-c">
  <div class="faq-q"><span class="faq-t">+</span>ow do I test whether an element has a particular class?</div>
  <div class="faq-a">
    <p>.hasClass() (added in version 1.2) handles this common use case:</p>
  </div>
</div>

2. The CSS/CSS3 to style the FAQ accordion.

.faq-header {
  font-size: 2em;
  border-bottom: 1px dotted #ccc;
  padding: 1em 0;
}

.faq-c {
  border-bottom: 1px dotted #ccc;
  padding: 1em 0;
}

.faq-t {
  line-height: 1em;
  color: #aaa;
  font-family: sans-serif;
  float: left;
  font-weight: 700;
  padding-right: 0.3em;
  -webkit-transition: all 200ms;
  -moz-transition: all 200ms;
  transition: all 200ms;
}

.faq-o {
  transform: rotate(-45deg);
  transform-origin: 50% 50%;
  -ms-transform: rotate(-45deg);
  -ms-transform-origin: 50% 50%;
  -webkit-transform: rotate(-45deg);
  -webkit-transform-origin: 50% 50%;
  -webkit-transition: all 200ms;
  -moz-transition: all 200ms;
  transition: all 200ms;
}

3. Include the latest version of jQuery library at the end of the document.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 

4. Enable the FAQ system with a little Javascript.

$(".faq-q").click( function () {
  var container = $(this).parents(".faq-c");
  var answer = container.find(".faq-a");
  var trigger = container.find(".faq-t");
  
  answer.slideToggle(200);
  
  if (trigger.hasClass("faq-o")) {
    trigger.removeClass("faq-o");
  }
  else {
    trigger.addClass("faq-o");
  }
});

This awesome jQuery plugin is developed by run-time. For more Advanced Usages, please check the demo page or visit the official website.