Reputation: 2887
For a FAQs section, my JS code checks whether the answer to the question clicked is visible and closes it if that's the case or opens it otherwise. But for some reason the (this_answer.is(':visible'))
condition is never true, even when the answer has been made visible by now by the fadeIn()
line in the code below. Why?
JS:
$('.faq_question').click(function(){
$('.faq_answer').fadeOut(0);
var this_answer = $(this).siblings('.faq_answer');
if (this_answer.is(':visible'))
this_answer.fadeOut(0);
else
this_answer.fadeIn(0);
});
HTML:
<ul>
<li>
<div class='faq_question'>
Question #1
</div>
<div class='faq_answer'>
Answer #1
</div>
</li>
<li>
<div class='faq_question'>
Question #2
</div>
<div class='faq_answer'>
Answer #2
</div>
</li>
...
Upvotes: 0
Views: 74
Reputation: 65806
You are fading all the answer elements out immediately, so they can't be visible right after that.
But, it appears that you may be trying to hide all the answers initially and then show them when the corresponding question is clicked. To do this, you should hide all the answers outside of the question click code and because you are using JQuery, just use .toggle()
to show/hide the answers without having to write any if/then
code.
Also, as others point out in the comments below. .fadeOut(0)
has the same effect as .hide()
, which is more straight-forward.
// Hide all the answers initially:
$('.faq_answer').hide();
$('.faq_question').click(function(){
// Just toggle the visibility of the answer(s) that
// correspond with the clicked question.
$(this).siblings('.faq_answer').toggle();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>
<div class='faq_question'>
Question #1
</div>
<div class='faq_answer'>
Answer #1
</div>
</li>
<li>
<div class='faq_question'>
Question #2
</div>
<div class='faq_answer'>
Answer #2
</div>
</li>
</ul>
Upvotes: 1
Reputation: 93571
As mentioned, you are hiding the item before checking if it is hidden. You can reduce it all to this:
// hide all the answers first
$('.faq_answer').hide();
// A single delegated event handler is more efficient
$(document).on('click', '.faq_question', function(){
// Toggle the matching answer for the clicked question
$(this).siblings('.faq_answer').toggle();
});
Upvotes: 1