I have a pretty basic jquery script which uses an h2 as a “trigger” to toggle the div below it.
Seen here:
$(".toggle-container").hide();
$("h2.trigger").click(function(){
$(this).toggleClass("active").next().slideToggle("slow");
return false;
});
I’ve tried to create a “toggle all” link but what happens is the divs that are open or closed aren’t being recognized, so it will have the opposite effect. Here is that code:
$("p.toggle-all a").click(function(){
$("h2.trigger").toggleClass("active");
$(".toggle-container").slideToggle("slow");
});
Basically when the p.toggle-all a is clicked, I’d like it to recognize if the toggled divs are closed and if so, open them. Or, if they are open to close them.
Hopefully that makes sense. Any help or advice is greatly appreciated!
My read of your question is that if any of the items is closed, you want the “all” button to open them; and if all are open, you want it to close them. If you really just want to invert their states, hunter has you covered. 🙂
But if I’ve read you right, this should do it:
I’ve used
$(this).click();above for brevity, but I’m not a fan of triggering event handlers from code. I’d rather have a function (say,toggleState) that is called from theclickhandler and from the code above. But it’s a style choice, and certainly if you’ve hooked up the handler with jQuery, you know you can callclickand trigger it.