First, I'd suggest the following structure for your faq's:
<div id="faq">
<div class="qa" id="faq_greenandflies">
<span class="q">What is <a href="#faq_greenandflies">green and flies</a></span>
<div class="a">
Super Pickle!
</div>
</div>
<div class="qa" id="faq_redandbadforteeth">
<span class="q">What is <a href="#faq_redandbadforteeth">Red and bad for your teeth</a></span>
<div class="a">
a Brick
</div>
</div>
<!--
More FAQ's here
-->
</div>
and then defining your jQuery as follows:
<script type="text/javascript">
$(function(){
// hide all answers
$('div#faq .qa .a').hide();
// bind a click event to all questions
$('div#faq .qa .q a').bind(
'click',
function(e){
// roll up all of the other answers (See Ex.1)
$(this).parents('.qa').siblings().children('.a').slideUp();
// reveal this answer (See Ex.2)
$(this).parents('.qa').children('.a').slideDown();
// return true to keep any other click events
return true;
});
// check location.hash to see if we need to expand one (direct link)
$(location.hash).find('.q a').click();
});
</script>
Explanation:
(Ex.1)
- this is the link that was clicked
- get the element that contains this and has a class of 'qa' (the box that contains both question and answer)
- select all of its siblings. (we now have all qa's as a jQ object)
- hide the answers
(Ex.2)
- this is the line or link that was clicked
- get the element that contains this and has a class of 'qa' (the box that contains both question and answer)
- reveal the answer
A working demo is here.
This does several things for you:
- If a user deep-links to an answer, the answer is automatically revealed
- If a user clicks on one answer, all other answers are hidden
- You can give your divs proper ids, so which helps search engine optimization of links to individual answers