Fading Banner Animation in jQuery

Recently, a company who will remain nameless has made their mobile devices incompatible with Flash. An alternative to Flash for simple animations is the use of jQuery. JQuery has gained popularity because of its reduced syntax, and cross-browser compatibility. Javascript syntax will vary depending on the user’s browser, leaving you to write a lot of try/catch code to accommodate for these variations. Not to mention testing the all the available browsers can be exhaustive.

I created a simple jQuery function I call jZugAnimate to show how a fading banner animation can be achieved. You can copy the code below, view the jZugAnimate sample page or download the jZugAnimate source.

To create the animation yourself, copy the code below into your javascript folder:
/javascript/jZugAnimate.js

function jAnimateDiv(divNameArray, transitionDelay, animationDelay, currentSlideNumber) {

    var slideCount = divNameArray.length;

    // Checking if first run - currentSlideNumber should be null
    if (typeof (currentSlideNumber) == 'undefined') {
        // Setting css for parent div
        $("#" + divNameArray[0]).parent().css({ position: "relative" });

        // Displaying first frame
        $("#" + divNameArray[0]).css({ opacity: '1', display: 'block', position: 'absolute' });

        for (i = 1; i < slideCount; i++) {
            // Initializing elements - hiding other frames
            $("#" + divNameArray[i]).css({ opacity: '0', display: 'block', position: 'absolute' });
         }

        // Call first transition after initial delay
         setTimeout(function () { jAnimateDiv(divNameArray, transitionDelay, animationDelay, 0); }, animationDelay + transitionDelay);

         // Exit the function without animating
        return;
    }

    // Getting Array Indexes
    var nextSlideNumber = (currentSlideNumber + 1) % slideCount;
    var prevSlideNumber = ((currentSlideNumber) == 0) ? slideCount - 1 : currentSlideNumber - 1;

    // Hiding third slide down
    $("#" + divNameArray[prevSlideNumber]).css("opacity", 0);

    // Bringing new slide in front of the old
    $("#" + divNameArray[currentSlideNumber]).css("zIndex", 4);
    $("#" + divNameArray[nextSlideNumber]).css("zIndex", 5);

    // Fading in the slide
    $("#" + divNameArray[nextSlideNumber]).animate({ opacity: 1.0 }, transitionDelay);

    // Calling next animation
    setTimeout(function(){jAnimateDiv(divNameArray, transitionDelay, animationDelay, nextSlideNumber);}, animationDelay + transitionDelay);
}

Although the jAnimateDiv function has four parameters, it should be called by its first three so it can properly initialize the elements:

  • divNameArray – an array containing the names of the divs to animate.
  • transitionDelay – the time period in milliseconds to fade between frames
  • animationDelay – time period in milliseconds to display the frame (does not include the transition period).

The function takes in the name of the id’s of the divs in divNameArray, and the animation delays. The first step is to check if this is the first call to the function. This is why the fourth parameter should be ignored. To initialize the animation, it sets the css position of the first animation element’s parent to relative. Then, all the animation elements’ position css is set to absolute. The positioning combination keeps all the animation elements in the same place. After the initialization, the function calls a setTimeout to give the animation its first delay, then exits.

The second time the function is called, it calculates the previous and next slide’s position in the array index, based on the divNameArray‘s element count. It swaps the current and next slide’s z-index, putting the new slide in front of the old. Next, it sets the opacity animation, then calls itself again after the setTimeout delay.

Although the process is a bit complex, jZugAnimate’s usage is not. Here is a sample of the code you would use, assuming you have jZugAnimate.js in your javascript folder.

/index.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>jZugAnimate Sample</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js" type="text/javascript"></script>
    <script type="text/javascript" src="javascript/jZugAnimate.js"></script>

    <script type="text/javascript">
        $(document).ready(function () {
            var animationDelay = 500; // delay for showing div
            var transitionDelay = 1500; // delay for transitions
            var divNames = new Array("slide1", "slide2", "slide3", "slide4", "slide5"); // id of divs to animate

            jAnimateDiv(divNames, transitionDelay, animationDelay);
        });
    </script>

</head>
<body>
    <div style="height: 200px;">
        <div id="slide1"><img src="http://www.zugno.com/coderscooler/samples/jZugAnimate/images/1.jpg" alt="" width="200" height="200" /></div>

        <!-- Hiding these elements in case user has javascript disabled -->
        <div id="slide2" style="display: none;"><img src="http://www.zugno.com/coderscooler/samples/jZugAnimate/images/2.jpg" alt="" width="200" height="200" /></div>
        <div id="slide3" style="display: none;"><img src="http://www.zugno.com/coderscooler/samples/jZugAnimate/images/3.jpg" alt="" width="200" height="200" /></div>
        <div id="slide4" style="display: none;"><img src="http://www.zugno.com/coderscooler/samples/jZugAnimate/images/4.jpg" alt="" width="200" height="200" /></div>
        <div id="slide5" style="display: none;"><img src="http://www.zugno.com/coderscooler/samples/jZugAnimate/images/5.jpg" alt="" width="200" height="200" /></div>
    </div>
</body>
</html>

As long as your animation structure is set up like the one above, all you need is one function call to jAnimateDiv with your three parameters. A word of caution: Make sure you set the height on the parent div of your slide, otherwise anything write after that, will be hidden behind the animation.