views:

32

answers:

1

I updates a div content with some html via an ajax call, and I what to execute a function after all the images from the ajax response are loaded.

See the code below, #gridWrapper is coming from the Ajax response and it has a lot of thumbnail images.

success: function(Data){
 MyGrid.prepGridLayout(Data.html);
 $('#gridWrapper .thumbnail img').load(function(index) {
  MyGrid.updateCellWidth(this);
 });
 MyGrid.adjustGridWidth();
 MyGrid.animateGridLayout();
}

I need to execute the MyGrid.animateGridLayout(); only after all images are loaded. Currently MyGrid.animateGridLayout(); is executed before MyGrid.updateCellWidth(this); executes

How to make sure the MyGrid.animateGridLayout(); runs only after all images are loaded ?

+2  A: 

You could have the "load" handlers keep track of how many they've done.

success: function(Data){
  MyGrid.prepGridLayout(Data.html);
  var thumbs = $('#gridWrapper .thumbnail img'), tc = 0;
  thumbs.load(function(index) {
    MyGrid.updateCellWidth(this);
    if (++tc === thumbs.length) {
      MyGrid.adjustGridWidth();
      MyGrid.animateGridLayout();
    }
   });
}
Pointy