3

I have an array of images

var photos = ["images/bg01.jpg", "images/bg02.jpg", "images/bg03.jpg"];

I am cycling through this array and making them the background of a div based on a interval

$("#bgimg" + activeContainer).css({
        "background-image" : "url(" + photos[i] + ")",
        "display" : "block",
        "z-index" : currentZindex
    });

EDIT: I need to preload all three images before I do my setInterval function.

Thanks in advance!!

RGilkes
  • 35
  • 4

3 Answers3

1
(function($) {
    var photos = ["images/bg01.jpg", "images/bg02.jpg", "images/bg03.jpg"];

    var i = 0;
    function preloadImage() {

        var image = new Image();

        image.onload = function() {
            $("#bgimg" + activeContainer).css({
                "background-image" : "url(" + photos[i] + ")",
                "display" : "block",
                "z-index" : currentZindex
            });

            i++;
            preloadImage();
        };

        image.src = photos[i];


    };

}(jQuery);

This will...

  1. load your image
  2. set it to background of your container
  3. repeat with next image
alex
  • 479,566
  • 201
  • 878
  • 984
  • Sorry, edited orignal post. Your code is great, but I have an interval changing the CSS so I need to preload all images before running my setInterval function. THANKS for your help! – RGilkes Dec 05 '10 at 02:56
1

Set a variable to the number of images that have to be loaded. Decrement the counter each time an image finishes loading, and when the counter reaches zero, start showing the images.

function photoLoaded() {
    if(!--numPhotosLeft) {
        // start showing images
    }
}

var photos = ["images/bg01.jpg", "images/bg02.jpg", "images/bg03.jpg"];
var numPhotosLeft = photos.length;

for(var i = 0; i < photos.length; ++i) {
    var img = new Image();
    img.onload = photoLoaded;
    img.src = photos[i];
}
PleaseStand
  • 31,641
  • 6
  • 68
  • 95
0

You could do this:

var imgCount = images.length;
var counter = 0;
$.each(images, function(i, n) {
   // load each image
   $("<img />").attr("src", n)
               .load(function() {
                  counter++;
                  if(imgCount == counter) {
                     // all images have loaded
                     // call setInterval
                  }

              });
});
karim79
  • 339,989
  • 67
  • 413
  • 406