Search code examples
jqueryslideshowphoto-gallery

Photo Slideshow by fading between background-images


I'm trying to implement a slideshow on my site and having some difficulty. I opted to create a div to hold my photo(s) and use background-image to set the photo. All photos are named 1.jpg, 2.jpg ... 12.jpg.

enter image description here

Here's the div...

<div class="featureImg"></div>

...and the CSS:

#feature .featureImg {
    [...some styling...]

    background-image:url(../img/slideshow/1.jpg);
    background-position:center;
    background-repeat:no-repeat;
    background-size:cover;
}

I want there to be an image on page load, then have it fade through the photos. Here's the jQuery I have right now, but the following does not work:

  • They don't fade between each other

Here's the jQuery:

(function() {
    var curImgId = 1;
    var numberOfImages = 12; // Change this to the number of background images
    window.setInterval(function() {
        $('#feature .featureImg').css('background-image','url(/img/slideshow/' + curImgId + '.jpg)').fadeTo('slow', 1);
        curImgId = (curImgId + 1) % numberOfImages;
    }, 5 * 1000);
})();

Question: How can I fix this so that there is a photo on page load (like 1.jpg) and then fades from one photo to the next?


Solution

  • For the initial image not showing, you may be needing a width and height on the div if there is no content within the div. Hard to tell without seeing all the CSS being applied to that div.

    For the fading: The fadeTo() in jQuery only sets the opacity of an element once. I believe your desired effect is that between switching photos, the first photo fades out, and switches, then the second photo fades in.

    This could be achieved using the callback function in the fadeTo(). So call the first fadeTo() and fade it to 0 opacity, then for that fadeTo's callback, set the next background image and use the second fadeTo to bring it back up to opacity of 1.

    (function() {
        var curImgId = 1;
        var numberOfImages = 12; // Change this to the number of background images
        window.setInterval(function() {
          $('#feature .featureImg').fadeTo('slow', 0, function() {
            $(this).css('background-image','url(/img/slideshow/' + curImgId + '.jpg)').fadeTo('slow', 1);
          });
            curImgId = (curImgId + 1) % numberOfImages;
        }, 5 * 1000);
    })();
    

    See this codepen for an example: http://codepen.io/keithwyland/pen/BkJoh