spin.js introduction

published on September 4, 2011 in technical

Modern user interfaces need feedback. There are many types of feedback, one of them is that little rotating flower-like graphic that we all are familiar with. Today, we do not need to build that with a GIF, there is spin.js.

1. What is it good for

If you do not want to use animated GIFs, and you problably don't, spin.js is a good alternative to some UI feedback. It needs quite a modern browser, but hey, we all do. Let's give this script a bit of a closer look. 

2. Size

If compared to animated GIFs, this lilltle javascript prooves smaller  — 3K minified, 1,7K gzipped. This is already a good reason for using it.

3. How it should be used

Grab the code from the above link, then use this::

var opts = {
     lines: 12, // The number of lines to draw
     length: 7, // The length of each line
     width: 5, // The line thickness
     radius: 10, // The radius of the inner circle
     color: '#000', // #rbg or #rrggbb
     speed: 1, // Rounds per second
     trail: 100, // Afterglow percentage
     shadow: true // Whether to render a shadow

var target = document.getElementById('foo');
var spinner = new Spinner(opts).spin(target);

As stated, there are a lot of options abailable, which are quite handy.

4. jQuery plugin

If you think that a jQuery plugin might be better, because you are using things integrated wit that library, then here it is:

$.fn.spin = function(opts) {
     this.each(function() {
          var $this = $(this),
          spinner = $this.data('spinner');
          if (spinner) spinner.stop();
          if (opts !== false) {
               opts = $.extend({color: $this.css('color')}, opts);
               spinner = new Spinner(opts).spin(this);
               $this.data('spinner', spinner);
     return this;

5. Conclusion

I used it on mobile platforms lately, and it worked pretty well. No problems actually. Try it yourself!