user70192
user70192

Reputation: 14204

Updating Button Icon In Bootstrap

I have an app that uses Bootstrap 3. In that app, I have a menu aligned to the right of the screen. That menu can be seen in this fiddle. The code for the menu looks like this:

<div class="dropdown pull-right">
  <a id="myDrop" href="#" class="btn btn-default  dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" role="button" aria-expanded="false">
    <i class="glyphicon glyphicon-home"></i>
    <span class="caret"></span>
  </a>

  <ul id="myMenu" class="dropdown-menu" role="menu" aria-labelledby="myDrop">
    <li role="presentation" class="active">
      <a role="menuitem" tabindex="-1" href="#" data-target="#home">
        <i class="glyphicon glyphicon-home"></i>
        Home
      </a>
    </li>

    <li role="presentation">
      <a role="menuitem" tabindex="-1" href="#" data-target="#profile">
        <i class="glyphicon glyphicon-user"></i>
        Profile
      </a>
    </li>

    <li role="presentation">
      <a role="menuitem" tabindex="-1" href="#" data-target="#messages">
        <i class="glyphicon glyphicon-inbox"></i> 
        Messages
      </a>
    </li>

    <li role="presentation">
      <a role="menuitem" tabindex="-1" href="#" data-target="#settings">
        <i class="glyphicon glyphicon-cog"></i>
        Settings
      </a>
    </li>
  </ul>
</div>

The text beside each icon is not centered vertically. My real problem though is, when a user chooses a menu item, I want to update the icon that's shown in myDrop. The icon in myDrop should change to be the icon of the chosen menu item. I was able to get the text by using the following:

$('#myMenu li a').on('click', function () {
  var $this = $(this);
  var parent = $this.closest('li');
  var target = $this.data('target');
  var btn = $this.closest('.dropdown').find('.btn.dropdown-toggle');
  var str = $this.text() + " <span class='caret'></span>";

  parent.siblings().removeClass('active');
  parent.addClass('active');

  btn.html(str);
  $('#myTab a[href="' + target + '"]').tab('show');  
});

This selects the text though. It does not use the icon. I tried using jQuery's .find function. However, I kept getting undefined. I'm not sure what I was doing wrong.

Upvotes: 1

Views: 1172

Answers (1)

dave
dave

Reputation: 64657

You can just change:

btn.html(str);

to

btn.html($(this).html()).append("<span class='caret'></span>");

http://jsfiddle.net/wnje9zak/3/

Or, if you just want the icon, you could do:

btn.html('').append($(this).find('i').clone()).append("<span class='caret'></span>");

Upvotes: 3

Related Questions