3

I am trying to get a callback function to execute when jQuery Masonry has done its positioning magic, preventing a flash of unstyled content in my code.

For the purpose of testing, though, I am using a simple alert that isn't called at all.

var $jigsaw = $('#jigsaw');

$jigsaw.imagesLoaded( function(){
    $jigsaw.masonry({
     columnWidth : 180,
      isAnimated : !Modernizr.csstransitions,
     isResizable : true,
    itemSelector : '.piece'
    }, function(){
        alert('Completed');
    });
});

I may be missing something obvious, but any help would be appreciated

Craig
  • 972
  • 3
  • 13
  • 38

4 Answers4

14

It looks like Masonry works with jQuery's deferred objects system. If you're using jQuery 1.5+ this might work:

$.when($jigsaw.masonry(options)).then(function(){/*callback function*/});
Anthony Veach
  • 320
  • 2
  • 10
  • Thank you so much for this answer - I've been looking for this line of code for about an hour at this point. I wish I could up this x10. Cheers. – MikeZ Dec 13 '14 at 01:24
3

Callbacks with Masonry v2.0 are undocumented and not quite supported.

But callbacks are awesome with Isotope v1.5! If you want proper callbacks that trigger after the end of a transition or animation, Isotope is the way to go.

The reason being is that you might be using CSS transitions or jQuery animation or neither. So I'd need to build in all the logic to detect which one is being used and then when to trigger the actual callback.

desandro
  • 2,854
  • 1
  • 22
  • 31
  • ... oh I have now masked Masonry with an image until it's loaded. Not ideal but good enough. Thanks – Craig Jun 08 '11 at 15:33
  • 1
    Desandro, first, thanks for a great plugin! Do you have any workarounds currently for this issue? I'm experiencing the same thing. – Paul Erdos Nov 30 '11 at 02:50
1
// Create the callback function
var callback = function($el, cb) {
  var instance = $.data($el, 'masonry');
  if (!instance) {
    setTimeout(callback($el, cb), 300);
  } else {
    cb();
  }
}

// Then simply add this to your imagesLoaded for an element of '.thumbnails' or something
callback('.thumbnails', function() {
  // some code goes here
});
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
tatatata
  • 11
  • 1
0

I tried this and it worked

jQuery.when( $jigsaw.masonry('reload') ).done(function(x) { 
    //call back logic 
});
Edward Falk
  • 9,991
  • 11
  • 77
  • 112
BlackEagle
  • 37
  • 4