rukasu
rukasu

Reputation: 25

jquery Icon Class Toggle on Click

When I click on 'arrow' icon, it toggles between classes 'up' and 'down', but since there are a lot of 'arrow' icons, when I click on another one, I would like the previous one to lose the class 'up'(if it has one) before adding it to the clicked 'arrow'. My JQUERY code seems to work fine except for this case scenario: enter image description here

*click arrow ('up' class is added)

*click another arrow ('down' class added to previous, 'up' added to clicked arrow)

*click another arrow ('down' class added to previous, the clicked arrow disappears)

My code:

$('.accordion').click(function() {
  if($(this).find('i').hasClass('fa-angle-down')){
      $('i').addClass('fa-angle-down');
      $(this).find('i').toggleClass('fa-angle-down fa-angle-up');
} else {
  $(this).find('i').toggleClass('fa-angle-up fa-angle-down');
}
});  

Any logic flaws in my function code.?

Upvotes: 0

Views: 842

Answers (2)

rukasu
rukasu

Reputation: 25

Found a solution with a help of @Cr1xus approach.

$('.accordion-question').click(function() {
  if($(this).find('i').hasClass('fa-angle-down')){
      $('i').addClass('fa-angle-down');
      $(this).find('i').removeClass('fa-angle-down').addClass('fa-angle-up');
} else {
  $(this).find('i').addClass('fa-angle-down').removeClass('fa-angle-up');
}
});

Upvotes: 1

Cr1xus
Cr1xus

Reputation: 437

$('.accordion').click(function() {
  if($(this).find('i').hasClass('fa-angle-down'))
      $(this).find('i').removeClass('fa-angle-down').addClass('fa-angle-up');
  else 
      $(this).find('i').addClass('fa-angle-down').removeClass('fa-angle-up');
});

Upvotes: 0

Related Questions