Tuesday, May 12, 2009

Replacing images at time intervals

This post is somehow a continuation of our previous post on replacing images, but this post is one step closer to creating an image gallery using jQuery. In this post I will show you how to replace one image with another one in specific time intervals. For example: replacing image1.jpg with image2.jpg every 5 seconds.

In javascript, whenever one says “every X seconds” or “time intervals” s/he is talking about javascript’s setInterval() function and this post is no exception.

So, before we continue, we need to define where our images are coming from. Images URLs can be stored in javascript array or we could choose more elegant way and simply read them from HTML document.

Imagine we have this HTML markup:

<div id="myGallery">
  <img src="image1.jpg" class="active" />
  <img src="image2.jpg" />
  <img src="image3.jpg" />
</div>

We need to hide all images but class="active" one and overlay all of them on one another. Here is a CSS to do that:

#myGallery{
  position:relative;
  width:400px; /* Set your image width */
  height:300px; /* Set your image height */
}
#myGallery img{
  display:none;
  position:absolute;
  top:0;
  left:0;
}
#myGallery img.active{
  display:block;
}

Now, lets write jQuery function that will fade out currently active image and fade in the next image. Here is jQuery code:

function swapImages(){
  var $active = $('#myGallery .active');
  var $next = ($('#myGallery .active').next().length > 0) ? $('#myGallery .active').next() : $('#myGallery img:first');
  $active.fadeOut(function(){
    $active.removeClass('active');
    $next.fadeIn().addClass('active');
  });
}

And now all that’s left is to add setInterval() with our function and the time interval we want our image to fade out and fade in.

// Run our swapImages() function every 5secs
setInterval('swapImages()', 5000);

Now we have gallery/slideshow with images changing every 5 seconds. You can easily customize this jQuery script to create your own slideshow.

Here is how your final code should look like:

<html>
<head>
  <script src="jquery.js">
  </script>
  <script>
    function swapImages(){
      var $active = $('#myGallery .active');
      var $next = ($('#myGallery .active').next().length > 0) ? $('#myGallery .active').next() : $('#myGallery img:first');
      $active.fadeOut(function(){
      $active.removeClass('active');
      $next.fadeIn().addClass('active');
      });
    }

    $(document).ready(function(){
      // Run our swapImages() function every 5secs
      setInterval('swapImages()', 5000);
    }
  </script>
  <style>
    #myGallery{
      position:relative;
      width:400px; /* Set your image width */
      height:300px; /* Set your image height */
    }
    #myGallery img{
      display:none;
      position:absolute;
      top:0;
      left:0;
    }
    #myGallery img.active{
      display:block;
    }
  </style>
</head>
<body>
  <div id="myGallery">
    <img src="image1.jpg" class="active" />
    <img src="image2.jpg" />
    <img src="image3.jpg" />
  </div>
</body>
</html>

The code above is simplified.

26 comments:

  1. Please correct the Code Box formatting. It doesn't wraps the text and hide some portion of the code.

    enjoy :)

    ReplyDelete
  2. @Bindass Delhiite, that's only in FF, all other browsers wrap lines correctly. Simply copy from first line to the last and you'll get all of the code... :)

    Thanks for the heads up... it is appreciated...

    ReplyDelete
  3. I seem to be a bit dense this morning can't get this to work. I imported jquery 1.3.2 and then tried putting the jquery code in head, body or external js file but the code is never called from what I'm seeing.

    ReplyDelete
  4. @jpickering, Try putting the final javascript code into:
    $(document).ready(function(){
    setInterval('swapImages()', 5000);
    });

    Also make sure that your div has myGallery id:

    <div id="myGallery"></div>

    Or change the jQuery code accordingly...

    ReplyDelete
  5. @Uzbekjon, I copied the code exactly as you had it in the example to begin with but I'm not sure I'm calling setInterval in the right place:

    // add click handlers
    function swapImages(){
    var $active = $('#myGallery .active');
    var $next = ($('#myGallery .active').next().length > 0) ? $('#myGallery .active').next() : $('#myGallery img:first');
    $active.fadeOut(function(){
    $active.removeClass('active');
    $next.fadeIn().addClass('active');
    });
    }
    // Run our swapImages() function every 5secs
    setInterval('swapImages()', 5000);

    ReplyDelete
  6. I tried that and Firebug reported swapImages as not defined, even though I put the function swap inside the $(document).ready(function(){

    ReplyDelete
  7. @jpickering, your final javascript code should look like this:

    // include jquery.js file here

    // add click handlers
    function swapImages(){
    var $active = $('#myGallery .active');
    var $next = ($('#myGallery .active').next().length > 0) ? $('#myGallery .active').next() : $('#myGallery img:first');
    $active.fadeOut(function(){
    $active.removeClass('active');
    $next.fadeIn().addClass('active');
    });
    }

    $(document).ready(function(){
    // Run our swapImages() function every 5secs
    setInterval('swapImages()', 5000);
    });

    I will add how the final HTML & javascript code should look like into the post itself now... It was my mistake not including the final code there...

    ReplyDelete
  8. @Uzbekjon, In frustration I copy pasted your final code then adjusted for image paths but all I got was a static image. A went back to basics and put alert(''); inside $(document).ready and I was surprised to see the alertbox never triggers.

    ReplyDelete
  9. Here is some code, the trusty alert box should popup telling me that section of code has executed :

    $(document).ready(function(){
    alert('test');
    // Run our swapImages() function every 5secs
    setInterval('swapImages()', 5000);
    }

    ReplyDelete
  10. @jpickering, I was tweeted on twitter about an example use of this script at: http://www.ages.uz

    You can investigate the code and see what's going wrong and right...

    ReplyDelete
  11. Ok thanks I got it working now, by viewing the source on that site by removing the $(document).ready(function(){ block completely and just coding it like regular JavaScript.

    ReplyDelete
  12. I just realized, That if you put the "$next.fadeIn()"
    on top of the "$active.fadeOut" function, You get a far nicer transition effect, because the "old" image is visible as backgrounfd then.

    Anyway: Great snippet! Thanx A Lot!!

    ReplyDelete
  13. Is it possible to do something like this but for swap the body background images? In this case I need to put a div with z-index: -9; right behind the main container and that causes the page to be the size of that div. For example, if the div is 1600 x 1200 it gives some extra width to the web I don't need. So if it's only the background of body, it won't affect the site at all. Anyways, it's a great tutorial and I might use it for something else in the future! Thanks.

    ReplyDelete
  14. I'm pretty new at this, and struggled to get jQuery set up and then to get this working. Eventually it worked when I replaced the $(document).ready(function(){ section completely with:
    window.onload = swapImages;
    setInterval(swapImages,4000);
    Now that it's working, thanks alot for the code.

    ReplyDelete
  15. Can you suggest anything for the following scenario:

    I have a div with an image as a css background...
    inside that, i have a png frame as a img, that will cut the edges of the background...

    What should i do to change the background with the same effect? or is it impossible ?

    ReplyDelete
  16. im trying to do something similar. except im just wanting to swap 1 image for another and for it to only happen just the one time. how would this be possible? can the above be changed slightly to achieve this. sorry im new to this.

    ReplyDelete
  17. $(document).ready(function(){
    // Run our swapImages() function every 5secs
    setInterval('swapImages()', 5000);
    } //needs a closing ');'

    Missing a ' ); ' at the end of this function...

    Works fine afterwards!

    ReplyDelete
  18. Sorry for jumping in but it seems I've found mistake.

    Instead this code:
    "
    $(document).ready(function(){
    // Run our swapImages() function every 5secs
    setInterval('swapImages()', 5000);
    }
    "
    you should add this code:

    "
    $(document).ready(function(){
    // Run our swapImages() function every 5secs
    setInterval('swapImages()', 5000);
    });
    "

    ReplyDelete
  19. Anyway to make each image be a link?

    ReplyDelete
  20. superb, this is what I looking for. Thank you!

    ReplyDelete
  21. I made the exact same page in html. can't get mine to work. I simply changed image 1, image 2, image 3 to their respective names. Do I have to download more

    ReplyDelete
  22. thanks man, finally someone that can explain a simple jquery command clearly... You're a star

    ReplyDelete
  23. it didn't work for me either until i fixed line 17:


    17 });

    ReplyDelete
  24. How do I slow down the fadeout for a longer transition effect?

    ReplyDelete
  25. This is great! I have question, I need to have a button that allows the user to start the rotating images over from the beginning. Is this possible? Can you please point me to some documentation or code snippet example? Thanks!

    ReplyDelete
  26. $(document).ready(function(){
    // Run our swapImages() function every 5secs
    setInterval('swapImages()', 5000);
    }); -->>

    // see -->> line ending correctly with brace and semicolon then it executes. try now.

    am ravali. k.ravali16@gmail.com

    ReplyDelete