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.