jQuery Masonry and Ajax Append Items?

Andy picture Andy · Jan 4, 2012 · Viewed 51.8k times · Source

I am trying to use some ajax and the jQuery Masonry plugin to add some items - but for some reason the new items aren't getting the masonry applied ?

I'm using

jQuery.ajax({
    type: "POST",
    url: ajax_url,
    data: ajax_data,
    cache: false,
    success: function (html) {
        if (html.length > 0) {
            jQuery("#content").append(html).masonry( 'appended', html, true );
        }
    });
});

However the items that are appended subsequently don't have the class="masonry-brick" applied which means that they stuff up completely the positioning ?

Answer

ryanlahue picture ryanlahue · Jan 4, 2012

It appears that the masonry function expects a jQuery object as its second parameter and not a raw HTML string. You should be able to fix this by wrapping the success callback parameter like so:

jQuery.ajax({
    type: "POST",
    url: ajax_url,
    data: ajax_data,
    cache: false,
    success: function (html) {
        if (html.length > 0) {
            var el = jQuery(html);
            jQuery("#content").append(el).masonry( 'appended', el, true );
        }
    });
});