Use jQuery to Animate Background Color

Although CSS keyframes is probably the easiest way to animate the background color of an element on the page, since earlier versions of Internet Explorer (IE < 10) don’t support CSS keyframes, if you need a more widely supported solution, you can do the same thing in jQuery.

To do this, you use the jQuery .animate() function.  The catch is that in order to be able to change colors with this function, you also need to include the jQuery Color plugin.

The way I did this in Rails was to just create a new file under assets/javascripts and called it jquery_color.js. Then copied the code from the plugin into that file.

Ok, now for the actual code. Credit for this goes to StackOverflow user fitorec‘s answer to this question, and this jsfiddle that he wrote.

$(document).ready(function() {
  var animate_loop, colors, i;
  colors = ['#FFB30C', '#58EC00', '#0087EC', '#EEEEEE', '#FF5A00'];
  i = 0;
  animate_loop = function() {
    $('body').animate({
      backgroundColor: colors[i++ % colors.length]
    }, 1500, function() {
      animate_loop();
    });
  };
  animate_loop();
});

This creates a colors array with the colors that you want to animate. Then it calls the .animate() function, passing in the backgroundColor property, and assigning it to one of the colors in the colors array, and iterates i to go through the array. The animate_loop function then calls itself, to create an infinite loop.

Of course if using Rails you can use js2coffee to convert to coffeescript.

Advertisements

One Response to Use jQuery to Animate Background Color

  1. Pingback: What I learned today | Use jQuery to Animate Background Color

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: