jQuery: fading background colors

One of the most interesting parts of jQuery is its ability of adding nice visual effects with a minimum effort. I was developing an Ajax validation system for a contact form and I was strucked by the fact that my error messages were pretty plain. When a user made a mistake, an error message appeared and when he actually inserted the correct values, then the message disappeared. I did want to add some color effect to this transition, so I wrote this simple plugin inspired by the code of Douglas Crockford:

(function($) {

    $.fn.fade = function(speed) {
        speed = speed || 100;
 var level = 1;
 var node = this;
 var step = function() {
     var hex = level.toString(16);
         backgroundColor: '#ffff' + hex + hex
     if(level < 15) {
         level += 1;
  window.setTimeout(step, speed);
 window.setTimeout(step, speed);


The transition is pretty simple: the box first turns yellow and then fades to white in a time span defined by the speed parameter. There are a few gotchas to keep in mind with this code. First, to properly get a reference to the jQuery element, I've created a variable called node and I've stored that reference in this variable. Second, the setTimeout() function has been called using its complete hierarchy path, starting from the global window object. This avoids us any possible scope problem. You can see the final result here.

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

Leave a Reply

Note: Only a member of this blog may post a comment.