Reputation: 368
So Im trying to build my small little accordion with some jquery Everytime I push the accordion they add a class open and remove the class closed. But now I want a maximum of 1 item open in the accordion. I can't figure out a way to build it inside my code.
I thought maby the else if statement when there is a open class already when you push the button it closes and it add to your current item a open class.
var accordion = ".accordion .section";
$(accordion).addClass("closed");
$(accordion).click(function(){
var $this = $(this),
$content = $this.find("ul");
if(!$this.hasClass("closed")){
TweenLite.to($content, 0.8, {height:0, ease: Power4.easeOut, y: 0 });
$this.addClass("closed");
$(accordion).append("closed")
$this.removeClass("open");
}
else {
TweenLite.set($content, {height: "auto"});
TweenLite.from($content, 0.87, {height: 0, ease: Power4.easeOut, y: 0});
$this.removeClass("closed");
$this.addClass("open");
}
});
Something like this.
Oh and for the (4) behind it, I also try to find a way to count the LI's inside 1 ul but I didn't really worked on that yet.
Small example I have build so far.
Upvotes: 0
Views: 69
Reputation: 28409
The issue is that you're not trying to close the others.
After opening/closing the clicked one, traverse up to .accordion
then select the items, exclude the one that was clicked on, and close them.
$(accordion).click(function(){
var $this = $(this),
$content = $this.find("ul");
if(!$this.hasClass("closed")){
TweenLite.to($content, 0.8, {height:0, ease: Power4.easeOut, y: 0 });
$this.addClass("closed");
$(accordion).append("closed")
$this.removeClass("open");
}
else {
TweenLite.set($content, {height: "auto"});
TweenLite.from($content, 0.87, {height: 0, ease: Power4.easeOut, y: 0});
$this.removeClass("closed");
$this.addClass("open");
}
// close the others
$(this).closest('.accordion').find('.section ul').not($content).each(function(){
TweenLite.to($(this), 0.8, {height:0, ease: Power4.easeOut, y: 0 });
});
});
I would suggest using CSS animation though, so you only have to toggle classes.
Upvotes: 2