Using masonry with Ajax reload

I  was struggling with masonry tonight. I know, it’s an old script and we should probably look out for something new, but still. I have this good ol’ website that uses ajax loading for search. It is triggered on the search (don’t forget e.preventDefault()) and will put what it finds in the inner element into the outer element. So far so good.

But what happens is dat the jQuery-object on which the Masonry-instance is working is now obsolete (on my site it is called $container, which captures #container. So this is important: Always make sure that you are excuting masonry on the right DOM-objects. When I added the statement $container = $("#container") after the AJAX-call was done loading (.done), things worked.

Also notice that I use imagesLoaded() to make sure masonry doesn’t start juggling DIV’s without knowing their proper sizes. Finally, consider blurring your search form’s input-field and don’t forget to bind the functionality you want to use after AJAX (there is life after AJAX). Note: this is the point where we scratch our head and sigh “perhaps we need some structured framework, after all, like node, angular, etc. Something that takes care of things.. But hey, if we follow proper practice, wrap and document our code properly, we can get a long way. At least vanilla javascript (or vanilla jquery) seems to be future-proof.

Code for reloading masonry after ajax call

$.get( url, { s: term }, function( data ){
$('#primary').html( $(data).find('#main') );
$container = $("#container");
})
.done(function() {
$container.imagesLoaded(function(){
if (typeof($container.masonry) !== 'undefined') $container.masonry();
if (typeof($container.ccb_ajaxbind) !== 'undefined') $container.ccb_ajaxbind();
});
// Blur input field
$("#searchform #s").blur();

Leave a Reply

Your email address will not be published. Required fields are marked *