A Simple jQuery Slide Show Plugin

I am working on a project that once again requires a slide show on the page. Previously, I posted on a more complex slide show that was configurable. This time everything is much simpler. I have a number of photos in a folder and want a simple slide show. Check out the demo:

Demo Download

I know…”Does the community really need another jQuery slideshow plugin?” Probably not! If you are looking for a nice slideshow plugin that supports many options I would look at the jQuery cycle plugin. If you want to look at some code and learn some jQuery, then follow along.

HTML and JavaScript

When using the plugin, I wanted the HTML and JavaScript to be minimal and clean. Here is the complete code (with CSS removed) for the demo page.

<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>jQuery Slide Show</title>
        <script type="text/javascript" src="scripts/jquery-1.4.1.js"></script>
        <script type="text/javascript" src="scripts/rlc.slideShow.js"></script>
        <script type="text/javascript">
            $(this).ready(function () {
                // Create the slide show
                var imageArray = ["KidsOnElbows.jpg", "KidsOnRail.jpg", "SoccerCoachAndKids.jpg", "TeacherAndStudents.jpg", "YoungFriends.jpg"];
                $("#slides").slideShow({
                    imageArray: imageArray,
                    imageRelativePath: "slides/"
                });
            });
        </script>
    </head>

    <body>
        <div id="wrapper">
            <div id="slides"></div>
        </div>
    </body>
</html>

Notice the HTML body tag is pretty empty. No image elements. Only two empty div’s. The outer div is only used for page formatting. The inner div (with the ‘slides’ ID) will old the slide. The HTML for the slides is created dynamically by the plugin. Now let’s look at the JavaScript.

First, jQuery and the slideshow plugin are pulled into the page. Then the jQuery ‘ready’ event handler is wired up with an anonymous function that creates the slideshow using the plugin. The plugin is configured by providing the following information:

  • A JavaScript array of photo file names
  • The relative path to the photo folder

That’s it. Simple and clean. Just how I like it. Now let’s look at the plugin.

jQuery Plugin

Here is the full plug-in:

(function ($) {

    $.fn.slideShow = function (options) {

        var defaults = {
            imageRelativePath: "/Content/images/slides/",
            imageArray: undefined,
            intervalMilliseconds: 7000,
            fadeInMilliseconds: 1000,
            fadeOutMilliseconds: 1000,
            cssClass: "slideshow"
        };

        var options = $.extend(defaults, options);
        var slideItems = undefined;
        var currentIndex = -1;
        var slideInterval = undefined;

        return this.each(function () {
            // ensure an image array exists
            if (options.imageArray == undefined) return;

            // create the slideshow dom
            var obj = $(this).attr("class", options.cssClass);
            var ul = $("<ul></ul>");
            for (var i = 0; i < options.imageArray.length; i++) {
                var itemHtml = '<li><img src="' + options.imageRelativePath + options.imageArray[i] + '" alt="slide"/></li>';
                ul.append($(itemHtml));
            }
            obj.append(ul);

            // start the slideshow
            ul.ready(function () {
                slideItems = $("li", obj);
                showNextSlide();
                slideInterval = setInterval(showNextSlide, options.intervalMilliseconds);
            });
        });

        // private functions
        function showNextSlide() {
            hideSlide(currentIndex, function () {
                currentIndex++;
                if (currentIndex >= slideItems.size()) {
                    currentIndex = 0;
                }
                showSlide(currentIndex);
            });
        }

        function hideSlide(index, callback) {
            if (currentIndex >= 0) {
                $(slideItems[index]).fadeOut(options.fadeOutMilliseconds, callback);
            } else {
                callback();
            }
        }

        function showSlide(index) {
            $(slideItems[index]).fadeIn(options.fadeInMilliseconds);
        }
    };

})(jQuery);

The plugin takes a few parameters as options. Most of them have supplied defaults. Here is a full run down on all the parameters:

  • imageRelativePath – The relative path to the folder containing the photos.
  • imageArray – A JavaScript array containing filenames of the photos
  • intervalMilliseconds – The time that each photo is displayed.
  • fadeInMilliseconds – The fade in time for each photo.
  • fadeOutMilliseconds – The fade out time for each photo.
  • cssClass – The class used to style the slide show.

The only two that really need to be set are the first two (that is if you don’t mind the other defaults).

Next, inside the jQuery ‘each’, the array is validated to exist. This section could use some beefing up. Then the DOM elements are created and added to the calling element. The HTML is simply an un-ordered list (‘ul’ / ‘li’) with each item containing an image (‘img’)

Once the DOM has been created and attached, the jQuery ‘ready’ function is used to determine when the elements have been loaded. Remember that the images will not be in the initial HTML request. These will only be fetched when the ‘img’ elements are attached to the main document. There may be some delay, depending on file size. By using the ‘ready’ function, we are insuring the images are ready.

The anonymous callback for the ‘ready’ function selects the list items into a local variable, shows the first slide, and then starts the slide show. Notice the jQuery selector uses a context parameter. This narrows the search space for jQuery and is much faster.

The private functions show / hide the slides and keep track of which slide is shown next.

Summary

Hope you find the code useful and informative. The download includes the plugin and sample CSS to get you started.

Comments
  1. LF4
  2. Aaron

Leave a Reply

Your email address will not be published. Required fields are marked *

*