I am making an FAQs section and I have some trouble with making the accordions act right.
When I click them one by one and close them before I open the next one, it's all fine. However if I open one, leave it open, and then click on the next one, the "show" class remains on the previous one.
I hope I am making myself clear, you can see what Im talking about in my code:
$(".js-accordion").click(function(e) {
e.preventDefault();
var $this = $(this);
if ($this.next().hasClass("show")) {
$this.removeClass("show");
$this.next().removeClass("show");
$this.next().stop().slideUp(350);
} else {
$this.addClass("show");
$this.parent().parent().find("div .accordion__inner").removeClass("show");
$this.parent().parent().find("div .accordion__inner").stop().slideUp(350);
$this.next().stop().toggleClass("show");
$this.next().stop().slideToggle(350);
}
});
.accordion__box {
max-width: 600px;
margin: 20px auto;
box-shadow: 0px 14px 20px 5px rgba(0, 0, 0, 0.1);
}
.accordion__inner {
overflow: hidden;
display: none;
padding: 10px 20px;
position: relative;
background-color: #fff;
border-bottom-left-radius: 5px;
border-bottom-right-radius: 5px;
}
.accordion__header {
border-radius: 5px;
font-weight: 900;
font-size: 24px;
font-family: "Lato", sans-serif;
margin-bottom: 0;
color: #fff;
display: flex;
justify-content: space-between;
background-color: #004a80;
padding: 20px 30px 20px 40px;
cursor: pointer;
transition: all 0.3s ease-in-out;
}
.accordion__header.show {
background-color: #EF2A72;
border-bottom-left-radius: 0;
border-bottom-right-radius: 0;
}
.accordion__header.show::after {
transition: all 0.3s ease-in-out;
transform: rotate(180deg);
}
.accordion__header::after {
content: "\f107";
color: #fff;
max-width: 30px;
height: 30px;
width: 100%;
border-radius: 5px;
display: flex;
align-items: center;
justify-content: center;
font-family: "Font Awesome 5 Pro";
font-size: 30px;
font-weight: 500;
transition: all 0.3s ease-in-out;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="accordion">
<div class="accordion__box">
<div class="accordion__header js-accordion">Who is this program for?</div>
<div class="accordion__inner">
<p>I’ve created this program for busy women of any age. No matter what your current weight… fitness level… or schedule looks like — this workout is for you. If you want to get a lifted, toned and curvy booty that’s also strong and athletic, this program
is yours.</p>
</div>
</div>
<div class="accordion__box">
<div class="accordion__header js-accordion">Why is this method better than others?</div>
<div class="accordion__inner">
<p>I’ve created this program for busy women of any age. No matter what your current weight… fitness level… or schedule looks like — this workout is for you. If you want to get a lifted, toned and curvy booty that’s also strong and athletic, this program
is yours.</p>
</div>
</div>
</div>