JSFiddle - React, Tailwind, and code Playground
by jfriend00
HTML
<div id="container"></div>
CSS
#container {
height: 266px;
width: 400px;
position: relative;
margin: 10px;
border: 1px solid #444;
}
#container img {
position: absolute;
left: 0;
top: 0;
display: none;
}
JavaScript
var urls = [
"http://photos.smugmug.com/Kenya/Highlights/Landscapes/i-vtH87Mv/0/S/JF2_3827-S.jpg",
"http://photos.smugmug.com/Kenya/Highlights/Landscapes/i-4W6qg3d/0/S/DSC_0613-S.jpg",
"http://photos.smugmug.com/Kenya/Highlights/Landscapes/i-CcfwBgG/0/S/DSC_0672-S.jpg",
"http://photos.smugmug.com/Kenya/Highlights/Landscapes/i-qWpr6LS/0/S/DSC_0772-S.jpg"
];
// preload images
function preloadImages(srcs, callback) {
var img, imgs = [];
var remaining = srcs.length;
for (var i = 0; i < srcs.length; i++) {
img = new Image();
img.onload = function() {
--remaining;
if (remaining <= 0) {
callback();
}
};
img.src = srcs[i];
imgs.push(img);
}
}
function runSlideshow(container, urls, fadeTime, delayTime) {
// all images are preload now
// start the slideshow
var imgs = $(container).append(new Image()).append(new Image()).find("img");
var curImage = 0;
var urlIndex = -1;
// no wait time for the first transition
var waitTime = 0;
function next() {
// set src on the next image
// fade out the current image
// fade in the new image
var nextImage = (curImage + 1) % 2;
urlIndex = (urlIndex + 1) % urls.length;
imgs.eq(curImage).delay(waitTime).fadeOut(fadeTime);
imgs.eq(nextImage).attr("src", urls[urlIndex]).delay(waitTime).fadeIn(fadeTime, next);
curImage = nextImage;
// set normal wait time for subsequent images
waitTime = delayTime;
}
next();
}
// preload the images and start the slideshow when they are all preloaded
preloadImages(urls, function() {
runSlideshow("#container", urls, 3000, 1000);
});