How to collapse all already expanded divs when expanding a collapsed div in jQuery?
I'm using this to expand or collapse some div
$("h3.trigger").click(function(){
$(this).toggleClass("active").next().fadeToggle(500,"swing");
return false;
});
on this html code
<div class="foo">
<h3 class="trigger active">Test 1</h3>
<div class="bloc开发者_StackOverflow中文版k" style="display:block">
<p>Lorem ipsum dolor </p>
</div>
</div>
<div class="foo">
<h3 class="trigger">Test 2</h3>
<div class="block" style="display:none">
<p>Lorem ipsum dolor sit amet</p>
</div>
</div>
<div class="foo">
<h3 class="trigger">Test 3</h3>
<div class="block" style="display:none">
<p>Lorem ipsum dolor sit amet.</p>
</div>
</div>
and everything works fine ;-)
But I would like to be able to collapse all div opened except the one opened by the h3 click !
Thanks for your help...
Chris
DEMO
$('.trigger').click(function() {
var d = $(this).next('.block');
check = (d.is(':visible')) ? d.slideUp() : ($('.block').slideUp())(d.slideDown());
});
This will allow you to even hide an opened one if you click it again! A smallest accordion script using TERNARY OPERATORS.
If you need help in understanding I can comment my code.
Here is the code with your .active
:
demo
$('.trigger').click(function() {
$('.active').removeClass('active');
$(this).addClass('active');
var d = $(this).next('.block');
check = (d.is(':visible')) ? d.slideUp() : ($('.block').slideUp())(d.slideDown());
});
How about this?
$("h3.trigger").click(function(){
$("h3.trigger").each(function() {
$(this).removeClass("active").next().fadeOut(500, "swing");
});
$(this).addClass("active").next().fadeIn(500,"swing");
return false;
});
You can also use the jQuery UI accordion, which I believe has an option for this behavior. (At least, I know I've done this with it before, but I don't recall specifically how and the site is on an intranet so I can't see it at the moment.)
What you need to do is to first close all of the toggled elements and then open the one that has just been clicked, but only if the one clicked is not currently open. The following code should do it:
$("h3.trigger").click(function(){
$(".foo").fadeOut(500,"swing");
if(!$(this).toggleClass("active").next().is(':visible')){
$(this).toggleClass("active").next().fadeIn(500,"swing");
}
return false;
});
精彩评论