I'm trying to do a simple rotating image on the home page. Under the hood I'm reading a directory and then populating urls for the images into an array. What I want to do is cross-fade the images. If it was just a matter of showing the next one, it's easy, but since I need to cross-fade, it's a bit harder. I think what I want to do is do the fades by calling animate() on the opacity value of the <img> tag, and in between swapping out the css background-image property of the enclosing <div>. But the results are not that great.
I've used tools for more full featured slideshows, but I don't want the overhead of adding a plugin if I can avoid it, and a simple crossfade seems like it should be easier.
Here's my JavaScript (I'm using jQuery 1.3.2):
var slideshow_images = ["http:\/\/example.com\/wordpress\/wp-content\/themes\/testtheme\/sidebar-home-bg\/bg1.jpg","http:\/\/example.com\/wordpress\/wp-content\/themes\/testtheme\/sidebar-home-bg\/bg2.jpg","http:\/\/example.com\/wordpress\/wp-content\/themes\/testtheme\/sidebar-home-bg\/bg3.jpg"];
var slideshow_index = 0;
var delay = 4000;
var swapSlides = function() {
var slideshow_count = slideshow_images.length;
// initialize the background to be the current image
$('#home-slideshow').css({
'background-image': 'url(' + slideshow_images[slideshow_index] + ')',
'background-repeat:': 'no-repeat',
'width': 200,
'overflow': 'hidden'
});
slideshow_index = ((slideshow_index + 1) == slideshow_count) ? 0 : slideshow_index + 1;
// fade out the img
$('#home-slideshow img').animate({opacity: 0}, delay);
// now, the background is visible
// next change the url on the img
$('#home-slideshow img').attr('src', slideshow_images[slideshow_index]);
// and fade it up
$('#home-slideshow img').animate({opacity: 1.0}, delay);
// do it again
setTimeout('swapSlides()', 4000);
}
jQuery(document).ready(function(){
if (swapSlides) {
swapSlides();
}
});
And here's the markup I'm using:
<div id="home-slideshow"><img src="http://example.com/wordpress/wp-content/themes/testtheme/sidebar-home-bg/bg1.jpg" alt="" /></div>