Chud37
Chud37

Reputation: 5017

Toggle Inline Chevron Down when activating bootstrap collapse

I'm not sure if the title made sense, but from PHP I'm echoing this HTML in a loop:

<a href='#' data-toggle='collapse' data-target='#myid'>
  <span class='fa fa-caret-down'></span>
</a>
<div id='myid' class='collapse'>Some Content</div>

I want the fa-caret-down to change to fa-caret-up when clicked, and vice versa. I want to the code to be inline, so I can output it in just this one instance. How can I do this?

Upvotes: 2

Views: 968

Answers (2)

Zakaria Acharki
Zakaria Acharki

Reputation: 67525

You could add the onClick inline event to your anchor and attach a function that toggles between classes to it like :

function toggleClass(self) {
  $('span', self).toggleClass('fa-caret-down fa-caret-up');
}
<link href="http://netdna.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<a href='#' data-toggle='collapse' data-target='#myid' onClick="toggleClass(this)">
  <span class='fa fa-caret-down'></span>
</a>
<div id='myid' class='collapse'>Some Content</div>

Suggestion

It will be better to use a common class in all of your anchors, and attach the click event to this common class, like :

<a href='#' data-toggle='collapse' data-target='#myid' class="icon_toggle">
    <span class='fa fa-caret-down'></span>
</a>
<div id='myid' class='collapse'>Some Content</div>

In your js code you should attach the click event that toggle between the both classes using the jQuery method toogleClass() like :

$('body').on('click', '.icon_toggle', function(){
     $('span', this).toggleClass('fa-caret-down fa-caret-up');
});

Upvotes: 2

Lasithe
Lasithe

Reputation: 2760

If someone's interested in handling this with Vanilla JS without using external libraries.

var carets = document.querySelectorAll('.up-down');

carets.forEach(function(caret){
  caret.addEventListener("click", function(){
     this.getElementsByTagName('span')[0].classList.toggle('fa-caret-down');
     this.getElementsByTagName('span')[0].classList.toggle('fa-caret-up');
  });
})
<link href="http://netdna.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" rel="stylesheet" />
<a href='#' data-toggle='collapse' data-target='#myid' class="up-down">
  <span class='fa fa-caret-down'></span>
</a>

<div id='myid' class='collapse'>Some Content</div>

Upvotes: 0

Related Questions