Simple Image SlideShow using jQuery

8:13:00 AM |


Note: This code was written when jQuery 1.3.2 was the latest version available. Currently we have jQuery 1.4.2 available.
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Simple Image SlideShow</title>
    <link href="../CSS/Demos.css" rel="stylesheet" type="text/css" />
    <script type='text/javascript'
        src='../Scripts/jquery-1.3.2.min.js'>
    </script>
  
    <script type="text/javascript">
        $(function() {    
                
            var imgs = [
                '../images/1.jpg',
                '../images/2.jpg',
                '../images/3.jpg',
                '../images/4.jpg'];
            var cnt = imgs.length;

            var $imageSlide = $('img[id$=imageSlide]');
            // set the image control to the last image
            $imageSlide.attr('src', imgs[cnt-1]);

            setInterval(Slider, 3000);

            function Slider() {
                $imageSlide.fadeOut("slow", function() {
                    $(this).attr('src', imgs[(imgs.length++) % cnt])
                    .fadeIn("slow");
                });
            }
        });
  
    </script>

</head>
<body>
    <form id="form1" runat="server">
    <div class="smallDiv">
        <h2>Image Slide Show - Image Changes Every 3 Seconds</h2><br />
        <asp:Image ID="imageSlide" runat="server" class="imgdiv" />
    </div>      
    </form>
</body>
</html>


This recipe shows you how to create a simple image slideshow that works in modern browsers. This example starts by declaring an array containing image paths. We have declared an image control on the page. When the page loads, the image path of this control is set to the last element of the array. I will explain shortly why this is needed.
var $imageSlide = $('img[id$=imageSlide]');
// set the image control to the last image$imageSlide.attr('src', imgs[cnt-1]);
We then use the JavaScript setInterval() function which delays execution of the Slider function for a specific time, in our case 3000 millisecond(3 seconds). The advantage of a setInterval()function is that it continues to repeat the process of triggering the function at a specified interval, thereby sliding the images in a cycle. If you want to pause the slideshow, use theclearInterval() function.
Note: Since the Slider function is first called after a 3 seconds delay, hence we explicitly set the image control source to the last image path in the array. If we do not do so, the user does not see an image for the first 3 seconds.
With every loop, we set the image control source to the next element in the array using the expression imgs[(imgs.length++) % cnt] and apply the fadeIn() and fadeOut() effect.
function Slider() {
    $imageSlide.fadeOut("slow", function() {
        $(this).attr('src', imgs[(imgs.length++) % cnt])
        .fadeIn("slow");
    });
}