A Simple jQuery Slideshow

8:29:00 AM |


In the interest of following jQuery’s motto of “writing less and doing more,” let’s write a simple slideshow using jQuery, JavaScript and a bit of CSS.
Simple jquery slideshow.
For starters, our main goal should be keeping the markup as clean as possible:




<div id="slideshow">
    <img src="img/img1.jpg" alt="" class="active" />
    <img src="img/img2.jpg" alt="" />
    <img src="img/img3.jpg" alt="" />
</div>
Now let’s use CSS to position the images on top of each other and bring the active image to the top level with z-index:

#slideshow {
    position:relative;
    height:350px;
}

#slideshow IMG {
    position:absolute;
    top:0;
    left:0;
    z-index:8;
}

#slideshow IMG.active {
    z-index:10;
}

#slideshow IMG.last-active {
    z-index:9;
}
Due to absolute positioning, we need to define the height of the slideshow DIV. Also, notice that we defined three different z-indexes—we will manipulate these soon using jQuery.
For the slideshow animation we are going to switch between each photo at a set rate. So let’s start by writing a function that brings in a new photo on top of the last active image:

function slideSwitch() {
    var $active = $('#slideshow IMG.active');
    var $next = $active.next();    

    $next.addClass('active');

    $active.removeClass('active');
}

$(function() {
    setInterval( "slideSwitch()", 5000 );
});
Here we set a JavaScript interval to call slideSwitch() every 5 seconds. Then slideSwitch() applies the CSS class ‘active’ to bring the next image to the top of the stack. Since we will select the images more than once within slideSwitch(), we define the variables $active and $next forselector performance.
Next we should incorporate a fade animation. For a gallery like this, fade in and fade out are identical, but let’s not forget to think about what we fade against:

function slideSwitch() {
    var $active = $('#slideshow IMG.active');
    var $next = $active.next();

    $active.addClass('last-active');

    $next.css({opacity: 0.0})
        .addClass('active')
        .animate({opacity: 1.0}, 1000, function() {
            $active.removeClass('active last-active');
        });
}

$(function() {
    setInterval( "slideSwitch()", 5000 );
});
We start by applying the ‘last-active’ class we defined earlier. Since ‘.last-active’ falls after ‘.active’ in the stylesheet, the z-index of 9 takes priority, and the top image drops back a level. Next, we set the opacity of the new image to 0 so that we can fade it in using the animate() function. Finally, we attach a callback to remove the z-index classes from the previous image when animate() completes.
Although our slideshow is working well, we should make it more robust by building in some default variables. First, let’s define a default active image, in case we need to put less stress on the back-end. Also, we can use defaults to make the gallery animation loop.

function slideSwitch() {
    var $active = $('#slideshow IMG.active');

    if ( $active.length == 0 ) $active = $('#slideshow IMG:last');

    var $next =  $active.next().length ? $active.next()
        : $('#slideshow IMG:first');

    $active.addClass('last-active');

    $next.css({opacity: 0.0})
        .addClass('active')
        .animate({opacity: 1.0}, 1000, function() {
            $active.removeClass('active last-active');
        });
}

$(function() {
    setInterval( "slideSwitch()", 5000 );
});
We first define a default image for the $active variable, which interestingly enough needs to be the last image on the stack. This is because through absolute positioning, the last image appears on top, and we need to start with it if we want to avoid any flicker.
For the loop it is pretty simple: all we have to do is point the $next variable to the first image once it has gotten to the end of the line.
If you want to improve this function, try setting the animation speed with a variable so the main slideshow function can be thrown into the core and left alone. Also, this slideshow is easily converted to support DIV’s instead of IMG’s—try programming a slideshow with more content.
Now for a challenge: the gallery flickers when the images first load, but it can be fixed without touching the JS or markup at all. Bonus points to whoever figures it out and posts a comment.