I am trying to customize a Bootstrap 4 accordion by conditional rotating the icon to point up when it is open and back down when closed. I managed to achieve this using CSS, but now I need to implement it conditionally based on active states rather than events triggering the accordions open.
Here is the HTML structure:
<div class="accordion" id="accordion-nav">
<div class="accordion-item">
<div class="item-header" id="heading">
<button class="btn btn-link btn-nav-accordion" type="button" data-toggle="collapse"
data-target="#collapseDosing" aria-expanded="false" aria-controls="collapseDosing">
<span>panel</span>
<i class="fas fa-chevron-down "></i>
</button>
</div>
<div id="collapseDosing" class="collapse collapse-nav-accordion"
aria-labelledby="heading-dosing" data-parent="#accordion-nav">
<div class="accordion-body">
<div class="l-accordion-body">
<h1>Body</h1>>
</div>
</div>
</div>
</div>
<div class="accordion-item accordion-item--savings">
<div class="item-header" id="heading-savings">
<button class="btn btn-link btn-nav-accordion" type="button" data-toggle="collapse"
data-target="#collapseSavings" aria-expanded="false" aria-controls="collapseSavings">
<span>panel</span>
<i class="fas fa-chevron-down"></i>
</button>
</div>
<div id="collapseSavings" class="collapse collapse-nav-accordion"
aria-labelledby="heading-savings" data-parent="#accordion-nav">
<div class="accordion-body">
<div class="l-accordion-body">
<h1>Body</h1>
</div>
</div>
</div>
</div>
</div>
In my CSS, I styled the icon rotation on click event, but looking for an alternative conditional way using JavaScript:
.btn-nav-accordion[aria-expanded="true"] {
.fa-chevron-down {
transform: rotate(180deg);
}
}
And here is my JavaScript code that currently works but does not remove the class upon closing the accordion:
$(".collapse-nav-accordion").each(function () {
var currentAccordion = this;
if ($(currentAccordion).hasClass("show")) {
$(currentAccordion).parent().find("i").addClass("rotate");
} else {
$(currentAccordion).parent().find("i").removeClass("rotate");
}
});