Cimbom
Cimbom

Reputation: 21

Is there an efficient way of doing jQuery toggle?

I was creating a FAQ section for my site, and, was wondering if there's more efficient way of toggling answers when the question is clicked. So far, I have the below code. However, it opens all answers when any question is clicked. If I wanna do it one by one, I have 100 question, and have to write 100 lines of toggle for answer-1, answer-2...So, is there a solution for this?

$(function(){
    $("a.question").click(function(){
    $("p.answer").toggle("slow");
 });
});

HTML + CSS:

a.question {display:block}
p {display:none}

<a class="question">Question 1?</a>
<p class="answer">Answer 1</p>

<a class="question">Question 2?</a>
<p class="answer">Answer 2</p>

<a class="question">Question 3?</a>
<p class="answer">Answer 3</p>

Upvotes: 2

Views: 217

Answers (1)

Femi
Femi

Reputation: 64700

$(function(){
    $("a.question").click(function(){
    $(this).next("p.answer").toggle("slow");
 });
});

Upvotes: 11

Related Questions