How to add a spinner icon to button when it's in the Loading state?

Leniel Maccaferri picture Leniel Maccaferri · Feb 10, 2013 · Viewed 415.7k times · Source

Twitter Bootstrap's buttons have a nice Loading... state available.

The thing is that it just shows a message like Loading... passed through the data-loading-text attribute like this:

<button type="button" class="btn btn-primary start" id="btnStartUploads"
        data-loading-text="@Localization.Uploading">
    <i class="icon-upload icon-large"></i>
    <span>@Localization.StartUpload</span>
</button>

Looking at Font Awesome, you see that there's now an animated spinner icon.

I tried to integrate that spinner icon when firing an Upload operation like this:

$("#btnStartUploads").button('loading');
$("#btnStartUploads i").removeAttr('class');
$("#btnStartUploads i").addClass('icon-spinner icon-spin icon-large');

but this had no effect at all, that is, I just see the Uploading... text on the button.

Is it possible to add an icon when the button is in the Loading state? Looks like somehow Bootstrap just removes the icon <i class="icon-upload icon-large"></i> inside the button while in the Loading state.


Here's a simple demo that shows the behavior I describe above. As you see when it enters the Loading state the icon just disappears. It reappears right after the time interval.

Answer

Flion picture Flion · Oct 9, 2014

Simple solution for Bootstrap 3 using CSS3 animations.

Put the following in your CSS:

.glyphicon.spinning {
    animation: spin 1s infinite linear;
    -webkit-animation: spin2 1s infinite linear;
}

@keyframes spin {
    from { transform: scale(1) rotate(0deg); }
    to { transform: scale(1) rotate(360deg); }
}

@-webkit-keyframes spin2 {
    from { -webkit-transform: rotate(0deg); }
    to { -webkit-transform: rotate(360deg); }
}

Then just add the spinning class to a glyphicon while loading to get your spinning icon:

<button class="btn btn-lg btn-warning">
    <span class="glyphicon glyphicon-refresh spinning"></span> Loading...    
</button>

Based on http://www.bootply.com/128062#

  • Note: IE9 and below do not support CSS3 animations.