Question

I need help in improving the background image slideshow. Go to JSFiddle, to see CSS.

The slideshow works fine, but I need to improve it by doing the following:

  1. Add fade out transition. Currently I managed to apply fade in effect, however, it fades in leaving white background underneath. I want images to fade smoothly between each other, not between the background.
  2. Pre-load the images in cache before the slideshow begins.

Note that each image has a caption, but I'm OK with it as it is. I don't need any transition for text.

JSFiddle http://jsfiddle.net/newsha/B4TXj/

var timer;
$(document).ready(function () {
    // background image on load
    var numberImages = 4
    var images = [];
    for (var i = 1; i <= numberImages; i++) {
        images.push(i);
    }
    var imgValue = 1
    $('.backgroundImage').addClass('bg' + imgValue + '');

    // Switch background image - forwards
    $('.imgSwitchRight').click(function () {
        $('.backgroundImage').each(function (e) {
            $(this).removeClass('bg1 bg2 bg3 bg4').fadeOut(0);
        });
        clearTimeout(timer);
        timer = setTimeout(function () {
            $('.imgSwitchRight').click();
        }, 8000);
        if (imgValue < numberImages) {
            imgValue++
        } else {
            imgValue = 1
        }

        $('.backgroundImage').addClass('bg' + imgValue + '').fadeIn(600);

    });
    clearTimeout(timer);
    timer = setTimeout(function () {
        $('.imgSwitchRight').click();
    }, 8000);

    // Switch background - backwards
    $('.imgSwitchLeft').click(function () {
        $('.backgroundImage').each(function (e) {
            $(this).removeClass('bg1 bg2 bg3 bg4').fadeOut(0);
        });
        clearTimeout(timer);
        timer = setTimeout(function () {
            $('.imgSwitchRight').click();
        }, 8000);

        if (imgValue > 1) {
            imgValue--
        } else {
            imgValue = numberImages
        }
        $('.backgroundImage').addClass('bg' + imgValue + '').fadeIn(600);

    });
    clearTimeout(timer);
    timer = setTimeout(function () {
        $('.imgSwitchRight').click();
    }, 8000);
});
Was it helpful?

Solution

Preload Images:

<script>   
function preloadImages(array) {
    if (!preloadImages.list) {
        preloadImages.list = [];
    }
    for (var i = 0; i < array.length; i++) {
        var img = new Image();
        img.src = array[i];
        preloadImages.list.push(img);
    }
}
var imageURLs = [
    "content/images/slideshowImage1.jpg",
    "content/images/slideshowImage2.jpg",
    "content/images/slideshowImage3.jpg",
    "content/images/slideshowImage4.jpg",
    "content/images/slideshowImage5.jpg"
];
preloadImages(imageURLs);
</script>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top