Tobias Tobias - 6 months ago 34
jQuery Question

Picture alignment with Isotope and imagesLoaded

Its my first post and i hope i didn't do anything wrong, if i did so please let me know.

I wanna load some flickr photos from a company account and have some problems with the alignment of the pictures.

I'm using Isotope to align the pictures in a proper manner. Now i'm facing the problem, that the pictures overlap when my site loads the first time. When i'm re-sizing the window, the pictures alignment is working and everything is fine but its doesnt solve my basic problem.
To fix the overlapping problem for the first call on the site, i tried to use the recommended imagesloaded.js but its not working.

First i thought its because i loaded the pictures via an asynchronous ajax call, so i changed my AJAX function to the following function but i'm facing still the same problem.

$.getJSON("https://api.flickr.com/services/feeds/photos_public.gne?id=125591374@N02&format=json&jsoncallback=?", function (data) {
console.log(data);
$("img").each(function () {
$(this).attr("src", data.items[i].media.m);
i++;
});
});


Here is my Isotope script

var $container = $('#picContainer');

$container.isotope({
itemSelector: '.picContainer-item'
, percentPosition: true
, layoutMode: 'masonry'
, masonry: {
columnWidth: 50
}
});

$container.imagesLoaded().progress(function () {
$container.isotope("layout");
});


I can't find the problem. Does anyone know, where did I something wrong?

I also prepared a codepen for a better understanding :)

Codepen example

Thanks!

Answer

What's happening is isotope is being loaded before all of your images are. So it's not setting the correct width until it renders it again (when you resize the window). If you place your isotope code inside a $(window).load(function(){}) (which runs only after all resources have been loaded), it will work.

$(window).load(function() {

  var $container = $('#picContainer');

    $container.isotope({
      itemSelector: '.picContainer-item'
      , percentPosition: true
      , layoutMode: 'masonry'
      , masonry: {
        columnWidth: 50
      }
    });

});

CodePen

(Also, you can remove the imagesloaded.js)