1

I am trying to toggle both the icon and the button text on a button and each function works independently, but they will not work when run consecutively. Seems that the function to toggle the button text is removing my icon altogether.

<button type="button" id="toggle-list-details">
    <i class="fa fa-list fa-lg"></i> 
    List View
</button>
$("#toggle-list-details").click(function() {
    $(this).text(function(i, text){
        return text === " List View" ? " Details View" : " List View";
      });                                
    $(this).find('i').toggleClass('fa-list fa-th-list'); 
)};
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
emailcooke
  • 271
  • 1
  • 4
  • 17
  • wrap your button text in a span and then `$(this).find('span').innerHtml('button text'); – Jacob Roberts May 15 '15 at 14:32
  • yes when setting text of your button, you remove the you need to be able to select the text only as Jacob Roberts suggested – bwright May 15 '15 at 14:34
  • As others have suggested using a `span` is the conventional way of doing this. If you don't want to add a new tag to wrap your text take a look at this question: http://stackoverflow.com/questions/298750/ – blgt May 15 '15 at 14:37

1 Answers1

3

When you do

$(this).text(function(i, text){ 

this reffers to <button type="button" id="toggle-list-details">, so it replaces all inner content with plain text.

To avoid this, you can do smth like this:

<button type="button" id="toggle-list-details">
    <i class="fa fa-list fa-lg"></i> 
    <span class="text">List View</span>
</button>

$("#toggle-list-details").click(function() {
    $(this).find('span').text(function(i, text){
        return text === " List View" ? " Details View" : " List View";
      });                                
    $(this).find('i').toggleClass('fa-list fa-th-list'); 
)};
Andriy
  • 973
  • 8
  • 13