jquery masonry images are overlapping until a page resize is done

Paul picture Paul · May 6, 2013 · Viewed 10.3k times · Source

I've found this template that demonstrates the issue I'm having with jquery masonry and image layout. Take a look at this twitter bootstrap template page:

The very first time the page is loaded all the images are stacked on each other until a page refresh or re-size is done. The images are then displayed correctly.

Here is my HTML and jQuery that has the same problem:

HTML

<div class="gallery-masonry masonry" style="position: relative; min-height:100px; height: auto;">
  <div id="loading">Loading ...</div>                            
</div>

jQuery

$.post("functions/photo_functions.php", { f: 'getallphotos'}, function(data) {

  $('#loading').hide();

    if(data) {  
      $.each(data.images, function(i, image) {
        var img_block = '<div class="item masonry-brick" style="position: absolute; top: 0px; left: 0px;">' +
        '<a href="#" class="thumbnail"><img src="'+image.url+'" alt=""></a>' +
        '<div class="actions">' +
        '<a title="" href="#" class="tip-top" data-original-title="Edit"><i class="icon-pencil icon-white"></i></a>' +
        '<a title="" href="#" class="tip-top" data-original-title="Remove"><i class="icon-remove icon-white"></i></a>' +
        '</div>' +
        '</div>';

        $(".gallery-masonry").append(img_block);
          });

        $('.gallery-masonry').masonry({
          itemSelector: '.item',
          isAnimated: true,
          isFitWidth: true
        });             
      }

    }, "json");

Any idea why this is happening and how might I fix it?

Answer

Tamil Selvan C picture Tamil Selvan C · May 6, 2013

Use imagesLoaded() to triggered masonry after all images are loaded. (imagesLoaded() is provided by the script http://github.com/desandro/imagesloaded.)

$('.gallery-masonry').imagesLoaded( function(){
  $('.gallery-masonry').masonry({
   itemSelector: '.item',
   isAnimated: true,
   isFitWidth: true
  });
});