0

I would like to change the arrow style on click.

When the accordion is closed, the arrow is down. When the user clicks the down arrow the accordion will open and the arrow will turn point up.

 <button type="button" class="btn btn-warning btn-sm " onclick="changeToggle(this)"><i class="fa fa-arrow-down" ></i></button> 


function changeToggle(btn) {
 $(btn).closest("tr").next().toggle();     
 $(btn).removeClass('fa-arrow-down').addClass('fa-arrow-up');
}

Normally in jQuery, if i know the id of the parent item I could use $("#id i") but because I used this as a parameter in the code.

I'm not sure how I can access the inside the button to change arrow style.

Allan Kimmer Jensen
  • 4,333
  • 2
  • 31
  • 53
AliAzra
  • 889
  • 1
  • 9
  • 28

1 Answers1

3

You just need to find the nested .fa of the button. You can use the context version of the $() for that, and then just toggle the classes back and forth.

function changeToggle (btn) {
  $('.fa', btn).toggleClass('fa-arrow-down fa-arrow-up');
}
.fa-arrow-down { color: red; }
.fa-arrow-up { color: green; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" class="btn btn-warning btn-sm " onclick="changeToggle(this)"><i class="fa fa-arrow-down">text for easy change</i></button>
Taplar
  • 24,788
  • 4
  • 22
  • 35
  • that's toggling button's class not updating font awesome icon – Aarif Mar 19 '19 at 12:16
  • Because I did not include the font awesome library. It is, however, showing the class updates because the text changes colors. – Taplar Mar 19 '19 at 12:16
  • better update this and include font awesome from cdn – Aarif Mar 19 '19 at 12:16
  • I gave an id to font awesome "Fawsm" updated a little bit like this: $(btn).find("#Fawsm").toggleClass('fa-arrow-down fa-arrow-up'); and it is working. Thank you Taplar. – AliAzra Mar 19 '19 at 12:26
  • @AliAzra better use `$('#Fawsm').toggle(...)`, directly – Aarif Mar 19 '19 at 12:28
  • Hi Aarif, I would love to use it directly but I have got the same button in each row and don't know which one user clicked. This is why i used btn – AliAzra Mar 19 '19 at 13:09
  • If you are repeating the id, then I would advise against that, as it is non-web compliant html. https://stackoverflow.com/questions/9454645/does-id-have-to-be-unique-in-the-whole-page – Taplar Mar 19 '19 at 13:10