I'm currently utilizing Bootstrap collapse in my project. I am attempting to implement a basic jQuery script that changes an icon once a user clicks on one of the collapses. Since there are multiple collapses on the page, I believe I need to use the "this" statement in my code.
Below is the HTML snippet:
<a data-toggle="collapse" href="#y2012" aria-expanded="false" aria-controls="y2012">
<i class="fa fa-caret-right"></i> 2012
</a><br />
<div class="collapse" id="y2012">
text
</div>
<a data-toggle="collapse" href="#y2013" aria-expanded="false" aria-controls="y2013">
<i class="fa fa-caret-right"></i> 2013
</a><br />
<div class="collapse" id="y2013">
text
</div>
Here is the current state of my JavaScript:
$(".collapse").hasClass("in") ? true : (function(){
$("a i").removeClass('fa-caret-right');
$("a i").addClass('fa-caret-down');
}, function () {
$("a i").removeClass('fa-caret-down');
$("a i").addClass('fa-caret-right');
});
---------------UPDATED---------------- I've made some progress and updated my JavaScript to this:
$('.collapsible').click(function () {
var $this = $(this);
$this.toggleClass('collapsible');
if ($this.hasClass('collapsible')) {
$this.children("i").removeClass('fa-caret-right');
$this.children("i").addClass('fa-caret-down');
} else {
$this.children("i").addClass('fa-caret-right');
$this.children("i").removeClass('fa-caret-down');
}
});
I have added the class "collapsible" to the anchor tag like so:
<a data-toggle="collapse" href="#y2012" aria-expanded="false" aria-controls="y2012" class="collapsible">
<i class="fa fa-caret-right"></i> 2012
</a><br />
While it somewhat works now, the issue is that upon first click on the anchor tag, the function does not trigger. It only starts working after clicking again, which goes against the intended behavior I initially wanted.