Set an Image object as a div background image using javascript

George Siggouroglou picture George Siggouroglou · Mar 20, 2012 · Viewed 33.9k times · Source

I want to load 4 images from background showing a load bar to the client
and when the images will be downloaded i want to set them as background images to 4 div blocks.

I am looking for something like this.

var myImages = new Array();
for(var i = 0; i < 4; i++)
    myImages[i] = new Image();
//load images using the src attribute
//and execute an on load event function where to do something like this.
var div0 = document.getElementById('theDivId');
div0.style.backgroundImage = myImage[index];

Is there any way to set a background image using an Image javascript object?

Answer

jfriend00 picture jfriend00 · Mar 20, 2012

You can do something close to what you had. You don't set an image background to be an image object, but you can get the .src attribute from the image object and apply that to the backgroundImage. Once the image object has successfully loaded, the image will be cached by the browser so when you set the .src on any other object, the image will load quickly. You could use this type of code:

var imgSrcs = [...];   // array of URLs
var myImages = [], img;
for (var i = 0; i < 4; i++) {
    img = new Image();
    img.onload = function() {
        // decide which object on the page to load this image into
        // this part of the code is missing because you haven't explained how you
        // want it to work
        var div0 = document.getElementById('theDivId');
        div0.style.backgroundImage = "url(" + this.src + ")";
    };
    img.src = imgSrcs[i];
    myImages[i] = img;
}

The missing part of this code is deciding which objects on the page to load which image into when the image loads successfully as your example stood, you were just loading each one into the same page object as soon as they all loaded which probably isn't what you want. As I don't really know what you wanted and you didn't specify, I can't fill in that part of the code.

One thing to watch out for when using the .onload event with images is you have to set your .onload handler before you set the .src attribute. If you don't, you may miss the .onload event if the image is already cached (and thus it loads immediately).