Reputation: 272
I'm experiencing an issue using the jQuery Masonry Plugin with an ajax call.
I have a filter function which is getting some pretty standard html content from the server (divs, no images):
var searchResults = $('div#results');
function filter() {
var text = 'text';
var orderby = 'order';
var source = 'source';
var media = 'media';
var format = 'format';
var tags = 'tags';
var fetchUrl = '/search/results/ ' + text + '/' + orderby + '/' + source + '/' + media + '/' + format + '/' + tags;
$.ajax({
type: "POST",
url: fetchUrl,
cache: false,
data: "after=000000",
success: function(data){
searchResults.html(data);
$('#results').masonry({
columnWidth: 360,
itemSelector: '.related'
});
}
});
}
This is then called on page load like so:
if (searchResults.length > 0) {
filter();
}
This is all working as expected. However, when I try and call filter()
from a click, it's getting the content fine but masonry isn't formatting it:
$('nav#view-types a#grid, nav#view-types a#list').click(function() {
filter();
return false;
});
As I'm calling masonry in the Ajax success function and it's working on the first run, I can't really see what the issue could be... anyone got any ideas?
Thanks!
James
Upvotes: 0
Views: 2665
Reputation: 1331
You need to tell masonry to "refire" after the ajax load finishes:
example:
$( document ).ajaxComplete(function() {
console.log("Ajax finished"); //remove this if you want, useful for debugging
$(document).ready(function() {
$('#content').masonry({
columnWidth: 260, //change this accordingly
itemSelector: '.item'
});
});
});
Masonry has a .reload() but I found it didnt really work well unless you were appending or prepending. To call it when completely changing the contents I had to do it like this.
Maybe a better solution here:
$(document).ready(function() {
$('#admin_content').masonry({
columnWidth: 260,
itemSelector: '.masonry-item',
isAnimated:true,
animationOptions: {
duration: 500,
easing:'swing',
queue :false
}
});
});
$( document ).ajaxComplete(function() {
$('#admin_content').masonry('reloadItems').masonry();
});
Upvotes: 3
Reputation: 4509
You need to call $('#results').masonry('reload') after you have appended your items.
Upvotes: 1