简体   繁体   中英

change button text and icon file (font awesome) on button click

I am trying to change the text of a button, as well as its associated icon file on click, and then reverse that on click again. I have got half way there and am able to toggle the class of the icon and the colour of the button, however if I try to change text or html of button it removes the icon reference. Is there a more efficient way to get this all done

html

<button type="button" class="btn btn-success btn-sm" id="newSale">
    <i id="iconChange" class="fa fa-plus"></i> add new
</button>

.js

$( "#newSale" ).click(function() {
  $( "#openNewSale" ).slideToggle( "slow", function() {
     $('#newSale').toggleClass('btn-success').toggleClass('btn-danger');
     $('#iconChange').toggleClass('fa-plus').toggleClass('fa-minus');
  });
});

You can check the display state of openNewSale using if($("#openNewSale").is(":hidden")) and change the classes accordingly

$( "#newSale" ).click(function() {
  $( "#openNewSale" ).slideToggle( "slow", function() {
     $('#newSale').toggleClass('btn-success').toggleClass('btn-danger');
      if($("#openNewSale").is(":hidden"))
      {
            $( "#newSale" ).html('<i id="iconChange" class="fa fa-plus"></i> add new');      
      }
      else
      {
          $( "#newSale" ).html('<i id="iconChange" class="fa fa-minus"></i> remove'); 
      }
  });
});

FIDDLE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM