Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bootstrap toggle button icon and text at the same time

I am using Bootstrap 3 with Jquery. I have a button that contains an icon in a span tag.(using glypicon of bootstrap)

<button id="swapArchived" class="btn btn-default btn-sm showArchived">
       <span class="glyphicon glyphicon-road"></span> Show Archived
</button>

I want to change the icon and text when clicked. Is there any better way other than,

$('#swapArchived').on('click', function () {
    var $el = $(this);
    if($el.hasClass('showArchived'))
    {
      $el.html('<span class="glyphicon glyphicon-fire"></span> Show Incomplete');
    }
    else
    {      
      $el.html('<span class="glyphicon glyphicon-road"></span> Show Archived');
    }
      $el.toggleClass('showArchived');
  });

I was curious whether I can toggle button text and span class at the same time. Trying to avoid writing span on every click.

Thanks-

like image 949
Jhankar Mahbub Avatar asked Dec 08 '22 11:12

Jhankar Mahbub


1 Answers

Try

jQuery(function ($) {

    $('#swapArchived').on('click', function () {
        var $el = $(this),
            textNode = this.lastChild;
        $el.find('span').toggleClass('glyphicon-fire glyphicon-road');
        textNode.nodeValue = 'Show ' + ($el.hasClass('showArchieved') ? 'Incomplete' : 'Archived')
        $el.toggleClass('showArchieved');
    });
});

Demo: Fiddle

like image 81
Arun P Johny Avatar answered Dec 11 '22 08:12

Arun P Johny