Random Image Display
HTML
<div class="parentContainer">
<div id="imageContainer">
</div>
</div>
<img class="displayImg" src="" />
CSS
.imageContainer {
width: 100px;
}
.displayImg {
width: 400px;
display: none;
}
JavaScript
//Object using the Revealing Module pattern for private vars and functions
var ImageRotator = (function() {
//holds the array that is passed in
var images;
// new shuffled array
var displayImages;
// The parent container that will hold the image
var image = $("#imageContainer");
// The template image element in the DOM
var displayImg = $(".displayImg");
var interval = null;
//Initialize the rotator. Show the first image then set our interval
function init(imgArr) {
images = imgArr;
displayImages = shuffle(images);
var firstImage = displayImages.pop();
displayImage(firstImage);
interval = setInterval(resetAndShow, 5000);
}
// If there are any images left in our shuffled image array then grab the one at the end.
// If there is an image present in the Dom, then fade out clear our image
// container and show the new image
function resetAndShow() {
if (displayImages.length != 0) {
var newImage = displayImages.pop();
if (image.find("#currentImg")) {
$("#currentImg").fadeOut(1500, function() {
image.empty();
displayImage(newImage);
});
}
} else {
clearInterval(interval);
}
}
// Show the image that has been passed. Set the id so that we can clear it in the future.
function displayImage(newImage) {
var newImg = displayImg;
newImg.attr("src", newImage);
image.append(newImg);
newImg.attr("id", "currentImg");
newImg.fadeIn(1500);
}
// Randomly shuffle an array
function shuffle(array) {
var currentIndex = array.length,
temporaryValue, randomIndex;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] =...