Reputation: 67
I have an accordion and when I click on the panels it toggles a couple of classes(.chevron--down, .chevron--up and .borderLeft). It works correctly when I open and close the same panel but when I click on a different panel it won't remove the classes from the previously clicked panel.
I have tried adding and removing the classes instead of toggling them. But it doesn't work.
$(".chevAcc, .card-header").on('click', function(ev) {
ev.preventDefault();
$(this).toggleClass('chevron--down chevron--up borderLeft');
})
.borderLeft {
border-left: 4px solid #2196f3;
}
.chevron--down,
.chevron--up {
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="">
<div class="card-header" id="headingEight" data-toggle="collapse" data-target="#collapseEight" aria-expanded="false" aria-controls="collapseEight">
<a class="chevron--down chevAcc">
<svg width="20" height="20" version="1.1" viewbox="0 0 100 100" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMidYMid">
<g class="chevron__container">
<line class="chevron__line1" x1="10" y1="50" x2="50" y2="50" />
<line class="chevron__line2" x1="90" y1="50" x2="50" y2="50" />
</g>
</svg>
</a>
<h2 class="mb-0"><button class="btn btn-link collapsed" type="button" data-toggle="collapse" data-target="#collapseEight" aria-expanded="false" aria-controls="collapseEight">FAQs</button></h2>
</div>
<div id="collapseEight" class="collapse" aria-labelledby="headingEight" data-parent="#accordionExample">
<div class="card-body">
Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird
on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw
denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
</div>
</div>
</div>
I expect that whenever I click on any of the panels the classes toggle properl and the classes from the previous clicked items are removed.
Upvotes: 0
Views: 132
Reputation: 780673
Select all the panels other than the current one, and set their classes the way they should be for a closed panel.
$(".chevAcc, .card-header").on('click', function(ev) {
ev.preventDefault();
$(".chevAcc, .card-header").not(this).removeClass('chevron--up borderLeft').addClass('chevron--down');
$(this).toggleClass('chevron--down chevron--up borderLeft');
})
Upvotes: 3