Image Rotator
HTML
<div class="parentContainer">
<div class="imageRotatorContainer">
</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;
// The parent container that will hold the image
var image;
// The template image element in the DOM
var displayImg = $(".displayImg");
var currentImgIndx;
var interval = null;
//Initialize the rotator. Show the first image then set our interval
function init(imgArr, parentContainer) {
parentContainer = $("." + parentContainer);
images = imgArr;
image = parentContainer.find(".imageRotatorContainer");
var firstImage = images[0];
displayImage(firstImage, 0);
interval = setInterval(resetAndShow, 5000);
setHandlers(parentContainer);
}
// 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() {
var newImage;
if (currentImgIndx !== images.length - 1) {
console.log("" + currentImgIndx);
currentImgIndx += 1;
} else {
currentImgIndx = 0;
}
newImage = images[currentImgIndx];
console.log("" + currentImgIndx);
if (image.find("#currentImg")) {
$("#currentImg").fadeOut(1500, function() {
image.empty();
displayImage(newImage, currentImgIndx);
});
}
}
// Show the image that has been passed. Set the id so that we can clear it in the future.
function displayImage(newImage, indx) {
var newImg = displayImg;
currentImgIndx = indx;
newImg.attr("src", newImage);
image.append(newImg);
newImg.attr("id", "currentImg");
newImg.fadeIn(1500);
}
function setHandlers(parentContainer){
parentContainer.on("mouseenter", removeInterval);
parentContainer.on("mouseleave", startInterval);
}
function removeInterval(){
clearInterval(interval);
}
function startInterval(){
...