jQuery: animating background colors

jQuery doesn't provide natively an option for animating background colors. In this post I'm going to show you how to accomplish this task with a little arrangement of my own. The first thing you need to do is basically the correct reading of the current value of the CSS background-color property. Thanks to the css() method we can do this in a very simple way. The value returned is in the RGB format, that is, rgb(red, green, blue), where red, green and blue are numeric values between 0 and 255. We can turn the returned value into an array and use each value as a counter to be used with a timer, like so:

$(document).ready(function() {

    var color = $('#test').css('backgroundColor');
    var baseColor = color.replace('rgb', '').replace('(', '').replace(')', '');
    var baseColors = baseColor.split(',');

    var red = baseColors[0];
    var green = baseColors[1];
    var blue = baseColors[2];

    var interval = window.setInterval(function() {

      $('#test').css('backgroundColor', 'rgb(' + red-- + ',' + green++ + ',' + blue++ + ')');

      if(red == 150) {

          window.clearInterval(interval);

      }

    }, 50);

});

As you can see, each value has been turned into a counter so that each time the timer runs these values change accordingly. We've set a limit, though: when the red value reaches 150, the timer stops. You can see a demo below.

Live demo

Live demo

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Comments are closed.