Spin.js, meet jQuery.colorbox

Spin.js can be used in a variety of settings, but often I find myself only including a spinner for projects when we’re also using colorbox. The two together are a perfect pairing!

Subject Matter
Development

Author

Published
October 25, 2013

Share
Facebook Tweet

One of my favorite under-utilized resources is the fantastic spin.js library. Forget your animated GIFs, weighing in at a light 4kb, this little javascript library makes loader style presentations easy to design and customize.

A tool we use a lot around the office is the ever-popular jQuery.colorbox, a lightweight modal presentation plugin for image galleries. It’s easy to style and even easier to implement. To top it off, it is well-maintained with regular incremental improvements that continue to make this widget shine!

By default, colorbox provides a basic GIF loader image. It’s simple to swap it out with your own custom GIF, but when you’ve exhausted the limited (although useful) options over at ajaxload.info or you’re looking for something a bit fresher, spin.js is a great dynamic alternative.

Hooking spin.js up to jQuery.colorbox is relatively easy. Utilize the colorbox onOpen and onComplete event listeners to set and unset the spinner.

$('#my_element').colorbox({
  onOpen: function() {
    $('#cboxOverlay').after('<div id="cboxSpinner" />');
    var target = document.getElementById('cboxSpinner');
    new Spinner(options).spin(target);
  },
  onComplete: function() {
    $('#cboxSpinner').remove();
  }
});

Because the colorbox element changes sizes when using the ‘elastic’ (default) transition, placing the spinner in that element creates some undesired effects with the spinner. Using the #cboxOverlay element is tempting, but opacity is set on that element, which might ultimately interfere with your design. The safest and cleanest solution is to dynamically create a new element just after the cboxOverlay and put the spinner there. You can control your layering via css and feel confident that your spinner will stay put! The simplest css for #cboxSpinner might look like this:

#cboxSpinner{
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
}

A full example can be found in the following jsfiddle. Feel free to play around with the options hash to see how easy it is to control the spinner style.