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 ?
Solution
I found a solution that works fine for me. it reloads every half second the layout of an instance of masonry.
this way, you can append things using ajax, and voilá, there is the masonry layout.
I had the same problem with my ajax listing, i could solve it by calling
reloadItems
&layouts
functions after ajax respond :You are missing Masonry layout call. According to the docs you need to refresh the layout, executing
.masonry()
after every change (for instance.masonry('appended')
):(source: http://masonry.desandro.com/methods.html)
it is clearly explained here https://masonry.desandro.com/methods.html#prepended
in your
success function
, you need your response "html" to be wrapped in ajquery object
and then append usinghtml()
orappend()
.the final code should be
For Masonry v3.2.2 (latest at the time of this post), this is what works:
Assuming newHtml is a string like this:
You process it like this:
Took me 2 hours to find out this!