tags:

views:

22

answers:

1

hello.. i have this code but i dont know what to do next..

var toBeInsertedToAS = "";

for(j=1;j<=10;j++)
{
    $('<img />')
    .attr('src','imgUrl_'+j+'.png')
    .load(function(){                
        toBeInsertedToAS += $(this).attr('src')+"|";                          
    });
    theSetDataCount++;
}    
alert(toBeInsertedToAS);

i just want to have this output..

imgUrl_1.png|imgUrl_2.png|imgUrl_3.png|etc...

but as what i can see, after the loop, there's no output.. maybe because it goes to alert(toBeInsertedToAS) without loading the pictures completely.. i just want to completely load the pictures first before it will execute the alert..

A: 

You can rearrange it a bit, like this:

var toBeInsertedToAS = [], theSetDataCount = 0;

for(j=1;j<=10;j++)
{
    $('<img />').one('load', function(){
                 toBeInsertedToAS.push(this.src);
                 if(toBeInsertedToAS.length == theSetDataCount)
                     alert(toBeInsertedToAS.join('|'));
              }).attr('src','imgUrl_'+j+'.png')
                .each(function() {
                  if(this.complete) $(this).load();
              });
    theSetDataCount++;
} 

You can test it here, this demo loads images from http://dummyimage.com/ as a source.

The load event happens when the image loads, not a synchronous thing, though it will be instant if it's from cache. From cache also won't fire the load event in some browsers...we're manually handling that with the .each() and the .one() ensures it only runs once, not affecting our count in a funny way.

The key here is to fire the alert() (or any other function) when the last load handler runs.

Nick Craver
thank you sir.. that solves my problem.. anyway, can i ask for the explanation for this var declaration? var toBeInsertedToAS = [], theSetDataCount = 0;
vrynxzent
ahh.. sir.. how about instead of alert(toBeInsertedToAS.join('|'));i will put the result first to a variable// then alert after the for loop// ?)like for(j=1;j<=10;j++){the code here that assigns the result to newVariable}alert(newVariable);
vrynxzent
because/.. all that code above.. the whole for loop, it still has the loop outside that loop.. so, maybe, the first result for that code must be put to a newVariable[0].. then next outside loop, the second result will be put to the newVariable[1]//is that posible sir?
vrynxzent
@vrynxzent - You can create multiple variables with a comma instead of `var ` each time, so it's equal to `var toBeInsertedToAS = []; var theSetDataCount = 0;`, making an empty array and int to use. If you put this inside a loop (that's a closure, say `.each()`), **including** the variables, they'll be per-loop and you can re-use them.
Nick Craver