Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery masonry images are overlapping until a page resize is done

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?

like image 877
Paul Avatar asked May 06 '13 02:05

Paul


2 Answers

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
  });
});
like image 125
Tamil Selvan C Avatar answered Nov 18 '22 11:11

Tamil Selvan C


The accepted answer has missing steps. So here is a step-by-step.

  1. Go to the imagesloaded repo and download the minified version at https://github.com/desandro/imagesloaded/blob/master/imagesloaded.pkgd.min.js.
  2. Add that library to your project.
  3. At the bottom of your page call the file

```[Adjust path to your javascript files]

<script src="/js/masonry.pkgd.min.js"></script>
<script src="/js/imagesloaded.pkgd.min.js"></script>

<script>
  $('.gallery-masonry').imagesLoaded( function(){
    $('.gallery-masonry').masonry({
     itemSelector: '.item',
     isAnimated: true,
     isFitWidth: true
    });
  });
</script>
like image 43
JGallardo Avatar answered Nov 18 '22 11:11

JGallardo