Library of The Week: spin.js

The spinning throbber is a standard UI element displayed on many websites when waiting for Ajax responses or other long-running operations. For a design-heavy marketing website, your graphic designer will probably tailor a fancy custom loading indicator. In other cases, a stock component is good enough.

One solution is use a pre-generated animated image. There are several libraries or generators to choose from. One disadvantage is that the throbber can't be transparent in this case, since the only widely supported animated image format is unfortunately still GIF, which doesn't support alpha channel.

An alternative is to use JavaScript and generate the throbber on the fly. That's purpose of this week's library: spin.js. The library is so simple (2.6kB compressed) that we can reproduce the full API here:

var opts = {
  lines: 13, // The number of lines to draw
  length: 0, // The length of each line
  width: 30, // The line thickness
  radius: 60, // The radius of the inner circle
  corners: 1, // Corner roundness (0..1)
  rotate: 44, // The rotation offset
  direction: 1, // 1: clockwise, -1: counterclockwise
  color: '#000', // #rgb or #rrggbb or array of colors
  speed: 0.5, // Rounds per second
  trail: 96, // Afterglow percentage
  shadow: false, // Whether to render a shadow
  hwaccel: false, // Whether to use hardware acceleration
  className: 'spinner', // The CSS class to assign to the spinner
  zIndex: 2e9, // The z-index (defaults to 2000000000)
  top: '50%', // Top position relative to parent
  left: '50%' // Left position relative to parent
var spinner = new Spinner(opts).spin(someDomElement);

These options allows you to customize the throbber in every imaginable way. Try it yourself with the live demo widget on the project page.

Roman Krejčík

Roman Krejčík