Create an FAQ Page with Show and Hide Questions and Answers using jQuery

This guide shows how to create a basic expandanle/contractable FAQ page using jQuery, html and CSS.

Just click the steps below to see the code or refer to the whole code snippet at the end. The CSS supplied is very basic to get the page started.

What jQuery do I need?
Include the latest jQuery
<script type="text/javascript" src="//code.jquery.com/jquery-3.6.0.min.js"></script>
If you are using a modern CMS such as WordPress or Drupal you can skip this as they already have jQuery pre-loaded.
What jQuery javascript code do I need?
<script>
 $(document).ready(function() {

	$('.faq_question').click(function() {

		if ($(this).parent().is('.open')){
			$(this).closest('.faq').find('.faq_answer_container').animate({'height':'0'},500);
			$(this).closest('.faq').removeClass('open');

			}else{
				var newHeight =$(this).closest('.faq').find('.faq_answer').height() +'px';
				$(this).closest('.faq').find('.faq_answer_container').animate({'height':newHeight},500);
				$(this).closest('.faq').addClass('open');
			}

	});

});
</script>
I need no-conflict jQuery javascript code for WordPress
<script>
jQuery(document).ready(function($)  {

	$('.faq_question').click(function() {

		if ($(this).parent().is('.open')){
			$(this).closest('.faq').find('.faq_answer_container').animate({'height':'0'},500);
			$(this).closest('.faq').removeClass('open');

			}else{
				var newHeight =$(this).closest('.faq').find('.faq_answer').height() +'px';
				$(this).closest('.faq').find('.faq_answer_container').animate({'height':newHeight},500);
				$(this).closest('.faq').addClass('open');
			}
	});
});
</script>
What HTML structure code do I need?
<div class="faq_container">
<div class="faq">
    <div class="faq_question">Question goes here</div>
        <div class="faq_answer_container">
            <div class="faq_answer">Answer goes here</div>
        </div>		
</div>
</div>
			
What CSS markup do I need?
<style>
/*FAQS*/
.faq_question {
	margin: 0px;
	padding: 0px 0px 5px 0px;
	display: inline-block;
	cursor: pointer;
	font-weight: bold;
}

.faq_answer_container {
	height: 0px;
	overflow: hidden;
	padding: 0px;
}
</style>

The Gist of It

1 Comment

  1. Oli on June 1, 2021 at 7:48 pm

    It doesn’t works!!!

Leave all Comment