Here goes -- the html base code itself is as follows:
<div class="blockQ">
<div class="q">
What's the answer to life, the universe and everything?
</div>
<div class="a">
42.
</div>
</div>
I chose to wrap the entire block - both question and answer - in a div to be able to hide and show entire blocks easily later.
Then, the jQuery actionscene.
$(document).ready(function() {
$('.a').hide();
$('.a:eq(0)').show(); //show only the very first answer
$('.q').click(function(){
$('.a').slideUp();
$(this).next().slideToggle(); //show the next element in the dom, which
//conveniently is the answer belonging to the clicked question
});
});
What this does is hide every answer, except the answer to the first question. Esthetics, really. Then, as soon as a question is clicked, the answer to that specific question slides into view, while the already visible one(s - you never know) slide out.Aight! Works fine!
But what if you have a thousand questions? Who will read them all? You want your visitors to be able to find the answer they need. In comes a search option. You could implement google for this, but I wanted it on the same page, unobtrusive and quick. You can style it any way you like, but if you take a simple input element like so:
...you can hook jQuery onto that with a key-up event, to search instantly as you type.
$('#search').keyup(function(){
var filter = $(this).val(); // Retrieve the input field text
$('.blockQ').each(function() // Loop through the questions/answers
// If the question and answer does not contain the text phrase fade it out
if ($(this).text().search(new RegExp(filter, "i")) < 0) {
$(this).hide();
} else {
$(this).show();
}
});
});
Smooth action!Then, to finish it off, a reset button to cancel your search phrase and show all the questions again.
function resetA() {
$('#search').val(""); //empty input element
$('.blockQ').show(); //show all questionblocks again
$('.a').hide();
$('.a:eq(0)').show(); //and show only the first answer.
};
There you have it! Check back for a working example soon, have to set up my hosting first ;)
No comments:
Post a Comment