Show/hide function for questions and answers

Here’s a neat little script that allows a question and answer type format, where the questions are all listed as links, and clicking on one toggles the visibility of the corresponding answer.

$("p").hide();
$("a").click(function () {
$(this).next("p:first").slideToggle("fast");
});

Here’s a version for lists that can be used to build an accordion navigation menu:

$("ul li ul").hide();
$("a").click(function () {
$(this).next("ul:first").slideToggle("fast");
});

Thanks to this post on Stackoverflow for the inspiration:

http://stackoverflow.com/questions/248320/using-this-with-jquery-selectors/248335

My selectors allow you to have multiple questions listed on one page. The answers given to the question on Stackoverflow only allowed for one, since, if clicked, it would toggle ALL of the paragraphs simultaneously.

This entry was posted in jQuery and tagged , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>