Animating a Twitter BootStrap Icon with CSS3

Introduction

So, I was already using Twitter Bootstrap on a project recently and I had a refresh icon that I wanted to use a button. The markup for my icon looked very much like the following snippet...

The previous markup renders as the following...

That is all fine and dandy, however, I thought it would be neat if the refresh icon would rotate when the clicked until that action was complete.

To implement this feature I decided to use a CSS3 animation.

Note: At the time of writing this CSS3 animation is currently supported in IE10, Firefox 16+, Chrome 23+, Safari 5.1+, Opera 12.1+, iOS 3.2+, Android 2.1+, & Blackberry 7.0+ Reference: Can I Use?

CSS3 Animation

If you don't already know about CSS3 Animation you can pick up a primer at the following locations...

I ended up using the following CSS to get the animation to work...

Note: You may have noticed that I'm not using vendor prefixes in the above CSS. For this demo I am using only the standard prefix-free styles and using Lea Verou's -prefix-free library to dynamically add the vendor prefixed styles at runtime. Now, you may or may not want to use this library for production, but it sure makes it nice for blog posts and jsFiddles!

The above CSS defines a class named icon-refresh-animate that assigns the animation, how long it should take, how many times it should iterate, and what type of algorithm to use. The class references the rotateThis keyframes which defines what the beginning and end state of the animation should look like. In this case the animation will rotate the element from 0 degrees to 360 degrees.

Once I got the CSS3 situated, I moved on to writing some JavaScript to wire up the animation. The following code snippet adds the icon-refresh-animation class to the icon when the anchor is clicked. Once the class has been added the animation begins. Then the code kicks off a window.setTimeout to simulate some kind of asynchronous action and when complete the class is removed, therefore stoping the animation.

You can interact with the final solution in the following jsFiddle. You'll need to click the icon in order to kick off the 2 second animation.

Conclusion

So, instead of looking for a GIF to animate your icon, why don't you try taking your ordinary element and make them come alive with a little CSS3 spice. Who needs animated GIFs anyway?

Now, get going and get your baby ninja talents to work. Okay, I admit animated GIFs are cool, but not for rotating your icons ;)