2

Possible Duplicate:
jQuery check if image is loaded

I have a situation where I have the following markup:

<div class="image">
    <img class="" src="content-images/1.jpg">
    <span class="slide" rel="content-images/2.jpg"></span>
    <span class="slide" rel="content-images/3.jpg"></span>
    <span class="slide" rel="content-images/4.jpg"></span>
</div>

Now in the CSS all the children of div.image are absolutely positioned so they're stacked on top of each other.

What I am doing is that, on a certain trigger, let's say when a button is clicked somewhere else on the page, to change the span's to img's with the src set to the rel in each span. The images are large high-res images so they could take a while to load completely.

Using javascript / jQuery I need to show a loading message / indicator from when the button is clicked to when all the span's being replaced with img's finish loading.

I can't use jQuery's .load() because of known issues with images and cache etc.

I tried using imagesloaded but it doesn't seem to do what I need.

Is there any other way to do this you can think of?

Community
  • 1
  • 1
Moin Zaman
  • 25,281
  • 6
  • 70
  • 74

1 Answers1

0

I'm not quite sure, if that's what you want to achieve, but you could give it a try...

$("#button").click(function(){
    console.log("Started loading...");
    // Get all spans to replace, and count them
    var imgSpans = $("div.image span.slide"), 
        toLoad = imgSpans.length,
        loaded = 0;
    // Now load each image
    for (var i = 0; i < toLoad; ++i) {
        // Closure to keep correct value of i
        (function(i){
            // Preload image
            var img = new Image();
            img.src = imgSpans.eq(i).attr("rel");
            img.onload = function(){
                // When loading has finished, replace span with img...
                imgSpans.eq(i).replaceWith(img);
                if (++loaded == toLoad) {
                    // ...and check if all images have been loaded by now
                    console.log("Finished loading...");
                }
            };
        })(i);
    }
});

DEMO (JSFiddle)

Aletheios
  • 3,960
  • 2
  • 33
  • 46