Help with toggle all functionality
I have a list where each element can be toggled open and closed like this
The list is like this:
<h2 class="siteDesSubTrigger"> <a href="#">Trigger</a></h2>
<div class="siteDesSubBlock" style="display: none;">
<ul>
<li>
Sub Content
</li>
</ul>
The jQuery is like this
$("h2.siteDesSubTrigger").click(function(){
$(this).toggleClass("active").next().slideToggle("slow");
return false;
});
I need to also add a Expand All/ Collapse All switch but I am having troubles getting this to work properly. This is what I h开发者_运维问答ave so far
$("h2.expandAll").click(function(){
$(this).toggle(function() {
$("h2.expandAll").text("Collapse All");
}, function(){
$("h2.expandAll").text("Expand All");
});
$(this).toggleClass("active");
$(".siteDesSubBlock").toggle();
});
but it is really buggy.. like if a panel is already expanded it will close it while opening the rest and.. well it basically doesnt work :P. Can someone please help me with the proper way to write this function?
The expand all could be rewritten to just use the click handlers of non-active h2's like so:
$('h2.siteDesSubTrigger').not('.active').click();
And the collapse all could be rewritten to just click active headers, eg.
$('h2.siteDesSubTrigger.active').click();
By implementing the expand/collapse all buttons like this, you leave each h2 click handler to deal with it's own toggle state and you shouldn't get into consistency issues.
firs of you should do this to make sure the link doesn't do default:
$("h2.siteDesSubTrigger").click(function(e){
e.preventDefault();
$(this).toggleClass("active").next().slideToggle("slow");
});
It works more properly in all browsers than return false
Here is how you do expand all and collapse all.
//expand all
$("h2.expandAll").click(function(e){
e.preventDefault();
$(".siteDesSubBlock").addClass("active");
$(".siteDesSubBlock").slideDown("slow");
});
//collapse all
$("h2.collapseAll").click(function(e){
e.preventDefault();
$(".siteDesSubBlock").removeClass("active");
$(".siteDesSubBlock").slideUp("slow");
});
I put it all on jsfiddle for you to view here: http://jsfiddle.net/jsweazy/MnnAf/
精彩评论