Reputation:
I've been trying to get an faq styled list created where there is a toggle button that when clicked slides open the respective answer to the question. However, I can't seem to get it to work at all and was wondering if I could have some help?
The main issue I'm having is when one button is clicked, they're all expanding and showing the answers. I was wondering if I could implement something so it targets the child element and toggles that?
Here is my code...
jQuery
$j("ul.nav .view_faq_answer").hide();
$j("a.toggler").click(function() {
$j(this).next('.view_faq_answer').slideToggle();
});
HTML
<ul class="faq">
<li>
<a href="#" class="toggler">+</a>
<div class="view_faq">
<div class="view_faq_question">question</div>
<div class="view_faq_answer">answer</div>
</div>
</li>
</ul>
I've stripped out the PHP so it's easier to see and obviously there's no need for any CSS as it's all styled up as it needs to be. I just don't know how to get this to work for each individual element.
I have tried (this).next and (this).parent but had no luck. Any help please?
Upvotes: 1
Views: 1662
Reputation: 841
Slightly more semantic HTML for this would be to use a <dl>
- with <dt>
as the question, and <dd>
as the answer.
Upvotes: 2
Reputation: 129
It's because .view_faq_answer
is not a sibling of .toggler
- it's a child of .view_faq
, which is a sibling. Robin Leboeuf's answer should work, but as an alternative:
$j(this).next('.view_faq').children('.view_faq_answer').slideToggle();
Edit: Fiddle
Upvotes: 3
Reputation: 2116
Try using .parent().find() instead of .next()
$("ul.nav .view_faq_answer").hide();
$("a.toggler").click(function() {
$(this).parent().find('.view_faq_answer').slideToggle();
} );
Upvotes: 1