jQuery: animating backgrounds

In this post I'm going to show you how to animate backgrounds with jQuery. For that purpose, I'm going to create a foreground element with some text inside and three background elements that appear and disappear in an infinite sequence. To accomplish this task, all elements must be absolutely positioned within a container with an appropriate z-index value, that is, the foreground element must have a value greater than background elements.

This is our CSS:

#panels {
    width: 60em;
    height: 20em;
    background: silver;
    position: relative;
    margin: 0 auto;
}

#panels h1 {
  font-size: 3em;
  letter-spacing: 0.1em;
  font-weight: normal;
  height: 1em;
  margin: 0;
  width: 5em;
  position: absolute;
  top: 50%;
  left: 50%;
  margin: -0.5em 0 0 -2.5em;
  text-transform: uppercase;
  text-align: center;
  z-index: 1;
}

div.panel {
  height: 100%;
  width: 20em;
  position: absolute;
  top: 0;
  display: none;
  z-index: 0;
}

.a {
  background: orange;
  left: 0;
}

.b {
  background: #fefef0;
  left: 20em;
}

.c {
  background: #d0fef0;
  left: 40em;
}

The three elements with the CSS classes panel, a, b and c will stay in background and we're going to reveal them just in time. The jQuery code, instead, is as follows:

$(document).ready(function() {


   var panels = '<div class="panel a"></div><div class="panel b"></div><div class="panel c"></div>';
   $(panels).insertBefore('#panels h1');
   
   
   function showPanels() {
   
   
       window.setTimeout(function() {
       
          
          $('#panels .c').fadeOut().prev().prev().fadeIn(1000);
          
          window.setTimeout(function() {
          
            $('#panels .a').fadeOut(1000).next().fadeIn(1000);
            
            window.setTimeout(function() {
            
            
                $('#panels .b').fadeOut(1000).next().fadeIn(1000);
            
            
            }, 1000);
          
          
          }, 1000);
       
       
       
       }, 1000);
   
   
   
   }
   
   window.setTimeout(function() {
   
   
     showPanels();
     
     window.setTimeout(arguments.callee, 3000);
   
   
   }, 1000);



});

First, we insert the three panels just before the title and then we animate them using nested setTimeout() calls wrapped within the showPanels() function. Finally, we call this function inside another setTimeout() function that calls itself, thus creating an infinite loop. Note that the time delay for this last function must be the sum of all time delays used in the previous timer calls.

Demo

Live demo

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

2 thoughts on “jQuery: animating backgrounds”

Leave a Reply

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