0

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?

Jon
  • 3,154
  • 13
  • 53
  • 96

1 Answers1

1

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

keithwyland
  • 2,998
  • 1
  • 17
  • 22
  • This works! Is there a way to fade the next photo in as the first one is fading out? – Jon May 08 '13 at 02:41
  • Well, so that's where this approach runs into an issue. You're fading the div, and not the image. To 'cross fade' you would need two separate elements on top of each other that contain the separate images so they could both be fading at the same time. – keithwyland May 08 '13 at 02:51