Asim Siddiqui
Asim Siddiqui

Reputation: 309

Onload Multiple Dynamic Images

function LoadPage (page) {
// each page contains 10 pictures
    var endp = page*10;
// Empty the main container that contains the pictures
    $('#container').empty();
// Rewrite the Page Menu
    for (j=1;j<Math.abs(len/10);j++) {
        $('#container').append("<a href='javascript: LoadData("+j+")'>"+j+"</a>");
    }
// Add the image containers containing images
    for (i=endp-10;i<endp;i++) {
            $('#container').append("<div class='container' id="+i+" >");
    $('#'+i).append("<img src="+x[i].getElementsByTagName('URL')[0].childNodes[0].nodeValue+" width='200'>");
        $('#container').append("</div>");
    }
// Have to call a function ' wall.reload(); ' once all the pictures are loaded!
    setTimeout(function(){
    if (wall) { wall.reload(); }
            },2000);
}

This function is called multiple times, each time with a page number. Everything is working fine. I am using a setTimeout() function to delay the function wall.reload() but I don't want to do that. Rather I want the function to wait till all the images are load and then fire wall.reload()

Thanks.

Upvotes: 3

Views: 587

Answers (2)

maximkou
maximkou

Reputation: 5332

function LoadPage (page) {
// each page contains 10 pictures
    var endp = page*10;
    // Empty the main container that contains the pictures
    $('#container').empty();
    // Rewrite the Page Menu
    for (j=1;j<Math.abs(len/10);j++) {
        $('#container').append("<a href='javascript: LoadData("+j+")'>"+j+"</a>");
    }

    // count of the loaded images
    var counterLoaded = 0;
    function waitReload(){
       counterLoaded++;
       // if all 10 images loaded
       if (counterLoaded == 10){
          if (wall){
             wall.reload();
          }
       }
    }

    // Add the image containers containing images
    for (i=endp-10;i<endp;i++) {
        $('#container').append("<div class='container' id="+i+" >");
        var img = document.createElement('img');
        img.src = x[i].getElementsByTagName('URL')[0].childNodes[0].nodeValue;
        img.setAttribute('width', '200');
        $('#'+i).append(img);
        $('#container').append("</div>");
        // if image loaded - increment loaded images counter
        img.onload = waitReload;
    }
 }

Upvotes: 0

Michael Kunst
Michael Kunst

Reputation: 2988

You could add an onload attribute to your image tag. There you would call a function such as imageLoaded(), which increments an imageCounter. If the imagecounter matches the amount of images you added it would call the wall.reload(). Code could look somewhat similair to the following:

var imagesLoaded = 0;
function imageLoaded(){
  imagesLoaded++
  if(imagesLoaded == numberOfImages)
    wall.reload();
  }
}

And in the image tag:

<img src="asdf.jpg" onload="imageLoaded()">

Upvotes: 1

Related Questions