I know this has been asked a thousand times but I’m still having trouble figuring it out. I have a simple according following this tutorial and I’m trying to add an “expand/collapse all” link. I have found a way to expand all but can’t figure out how to collapse them. The problem with a slideToggle() solution is if I open one then click the link it will close/open all of them but the one that was previoiusly active.
I set up a jsFiddle here.
Here is an overview of the code:
HTML:
<h2 class="acc_trigger"><a href="#">Div 1</a></h2>
<div class="acc_container">
<div class="block"> Yay content!</div>
</div>
<h2 class="acc_trigger"><a href="#">Div 2</a></h2>
<div class="acc_container">
<div class="block">More Content, Score!</div>
</div>
<h2 class="acc_trigger"><a href="#">Div 3</a></h2>
<div class="acc_container">
<div class="block">Even More Content</div>
</div>
<a href="#" class="acc_expand-all">Expand/Collapse All </a>
JS:
jQuery(document).ready(function($) {
//Set default open/close settings
$('.acc_container').hide(); //Hide/close all containers
//On Click
$('.acc_trigger').click(function(){
$('.acc_trigger').removeClass('active').next().slideUp();
//Remove all "active" state and slide up the immediate next container
$(this).toggleClass('active').next().slideDown();
return false; //Prevent the browser jump to the link anchor
});
$('.acc_expand-all').click(function(){
//expand all on click
$('.acc_trigger').addClass('active').next().slideDown();
return false;
});
});
You have to check in your expand/collapse handler to see how many are open, etc., something like this (updated fiddle):
Regarding your question in the comments, you can check to see whether you should be in “exclusive” mode or not by checking how many are open and whether the clicked one is open, e.g. (updated fiddle):