So why code your own? Simplicity and control are the main reasons. Unless you're already loading up a 3rd-party rotator library, why add to the bandwidth overhead? Some of those libraries can be quite time-consuming to get to grips with, so a roll-your-own solution can be quicker for simple transitions. Finally, when you know exactly what's happening, when and how, then you have more control over the final effect and can tweak it exactly as you wish.
So, without further ado, onto the code:
<img id="slideshow" src="../../images/demos/zoe.jpg" />
<script type="text/javascript">
var slideshowImages = ['awesome-pandas.jpg', 'Bobcat.jpg', 'dolphins.jpg', 'laughing-dog.jpg', 'fernsehturm.jpg', 'zoe.jpg'];
var slideshowIndex = 0;
function fadeoutSlide() {
$('#slideshow').filter(':not(:animated)').animate( {opacity: '0'}, 200, 'easeOutQuint', fadeinSlide );
}
function fadeinSlide() {
if (slideshowIndex >= slideshowImages.length) slideshowIndex = 0;
$('#slideshow').attr('src', '../../images/demos/' + slideshowImages[slideshowIndex++]);
$('#slideshow').animate( {opacity: '1'}, 200, 'easeOutQuint' );
}
</script>
In order to make the slideshow cycle smoothly between images, we need to preload them, using code such as that below:
<script type="text/javascript">
$(document).ready(
function() {
preload();
}
);
var preloading = false;
var safteyvalve = 1000;
function preload() {
if (document.images) {
// Set flag to indicate preload is occuring
preloading = true;
// Create an Image object for each image
imagePreloader = new Array();
for (var offset = 0; offset < slideshowImages.length; offset++) {
imagePreloader[offset] = new Image();
imagePreloader[offset].src = '../../images/demos/' + slideshowImages[offset];
}
// Check images in quarter of a second
window.setTimeout(checkpreload, 250);
}
}
function checkpreload() {
if (safteyvalve > 0) {
safteyvalve--;
} else {
preloading = false;
}
if (preloading) {
// Loop through image array to see if any are not yet loaded
preloading = false;
for (offset = 0; offset < imagePreloader.length; offset++) {
if (!imagePreloader[offset].complete) {
preloading = true;
break;
}
}
}
if (preloading) {
// Check again in another 0.25 secs
window.setTimeout(checkpreload, 250);
} else {
// Preloading complete - let dynamic shenanigans begin
window.setInterval(fadeoutSlide, 2800);
}
}
</script>
Click this link for more details on the image preloader.