Wednesday, February 23, 2011

FAQs with Jquery

Step 1.

Create a page with FAQs formatted in the following manner:

  <div class="faq">
<div class="question">Question here</div>
<div class="answer">Answer here</div>
</div>

Add an ordered list at the top of the page with id="questions":


<ol id="questions">
</ol>


Then, add this javascript to your page (with jQuery already loaded, of course):
<script type="text/javascript">
$().ready(function(){
$('.faq').each(function(index, value){
$('#questions').append($("<li>").append($("<a>").attr('href', '#faq' + index).text($(value).find('.question').text())));


$(value).find('.question').text((index + 1) + '. ' + $(value).find('.question').text());
$(value).find('.answer').after(
$("<a href='#' class='top'>Top</a>")
);
$(value).before($("<a name='faq" + index + "'></a>"));
});
});
</script>
And here's some CSS to make it look pretty:
<style>
ol#questions {
margin-left: 40px;
margin-bottom: 80px;
}

ol#questions li {
font-size: 16px;
line-height: 200%;
}

div.faq {
border-bottom: 1px solid #CCCCCC;
margin: 20px;
padding-bottom: 10px;
font-size: 16px;
}

div.question {
font-weight: bold;
color: #078CF9;
margin-bottom: 5px;
}
div.answer {
margin-bottom: 5px;
}
</style>


2008 joshnankin.com | Based on template from Free CSS Templates