Reputation: 23
I have question & answer section on my website (FAQ).
The HTML looks like this
<div class="faq">
<div class="container">
<!-- FAQ 1 -->
<h3><a href="">My FAQ 1</a></h3>
<div><p>Answer to MY FAQ 1</p></div>
<!-- FAQ 2 -->
<h3><a href="">My FAQ 1</a></h3>
<div><p>Answer to MY FAQ 1</p></div>
<!-- FAQ 3 -->
<h3><a href="">My FAQ 1</a></h3>
<div><p>Answer to MY FAQ 1</p></div>
</div>
</div>
And the jQuery looks like this
$(document).ready(function() {
$(".faq h3 a").click(function(){
$(this).parent().next().toggle();
return false;
})
});
This works fine but what I need is that if someone clicks on any one FAQ & that if any other FAQ is opened then the same should close automatically.
I tried doing this
$(".faq h3 a").not($(this)).hide();
But it does not work.
Upvotes: 2
Views: 59
Reputation: 5810
I guess this is what you want.
Explanation: Close them first and then open the clicked one.
Snippet:
$(document).ready(function() {
$(".container div").hide();
$(".container div:nth-of-type(1)").show();
$(".faq h3 a").click(function() {
$(".container div").hide();
$(this).parent().next().show();
return false;
})
});
.container {
background: #fff;
padding: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="faq">
<div class="container">
<!-- FAQ 1 -->
<h3><a href="">My FAQ 1</a></h3>
<div>
<p>Answer to MY FAQ 1</p>
</div>
<!-- FAQ 2 -->
<h3><a href="">My FAQ 1</a></h3>
<div>
<p>Answer to MY FAQ 1</p>
</div>
<!-- FAQ 3 -->
<h3><a href="">My FAQ 1</a></h3>
<div>
<p>Answer to MY FAQ 1</p>
</div>
</div>
</div>
Note: For transition effects you could use
slideToggle('slow,fast, x ms')
Upvotes: 0
Reputation: 1
maybe not the most elegant use of jQuery
$(document).ready(function() {
$(".faq h3 a").click(function(){
var isVis = $(this).parent().next().css('display') == 'block';
$(".faq h3 + div").hide();
$(this).parent().next().toggle(!isVis);
return false;
})
});
This should toggle correctly, i.e. click on an open FAQ it will close it
Upvotes: 1