Rich Armstrong
Rich Armstrong

Reputation: 1432

How do I get JQuery Masonry to recognize added items?

This is the same question as this one, but I have a repro of the issue on JSFiddle up here. So I thought I'd repost.

JQuery Masonry seems to only assess the children of its container once, on first run. After that, it's impossible to get it to look at the DOM again to get it to reassess its children.

Upvotes: 5

Views: 5812

Answers (4)

Pedro Moreira
Pedro Moreira

Reputation: 970

if you are using jQuery, this will solve all your problems.

You are including Masonry in your html/php page with something like this:

<script src="js/masonry.min.js"></script>
<script>
    $('#ms-container').masonry({
        columnWidth: '.ms-item',
        itemSelector: '.ms-item'
    });
</script>

Instead, leave it like this:

<script src="js/masonry.min.js"></script>
<script src="js/masonry-init.js"></script>

And create the js/masonry-init.js file with the following:

$('#ms-container').masonry({
    columnWidth: '.ms-item',
    itemSelector: '.ms-item'
});
var masonryUpdate = function() {
    setTimeout(function() {
        $('#ms-container').masonry();
    }, 500);
}
$(document).on('click', masonryUpdate);
$(document).ajaxComplete(masonryUpdate);

Never worry about it again!

Upvotes: 0

Tyler Collier
Tyler Collier

Reputation: 11988

I made use of the reload method:

.masonry( 'reload' )

Here's the masonry doc for reload:

"Convenience method for triggering reloadItems then .masonry(). Useful for prepending or inserting items."

Upvotes: 1

Rich Armstrong
Rich Armstrong

Reputation: 1432

I seem to have solved this by adding a line to reload the "bricks" to the _reLayout function in the JQuery Masonry code at line 305.

_reLayout : function( callback ) {

  // This is my added line. 
  // Items might have been added to the DOM since we laid out last.
    this.reloadItems();

  // reset columns
  var i = this.cols;
  this.colYs = [];
  while (i--) {
    this.colYs.push( this.offset.y );
  }
  // apply layout logic to all bricks
  this.layout( this.$bricks, callback );
},

// ====================== Convenience methods ======================

// goes through all children again and gets bricks in proper order
reloadItems : function() {
  this.$bricks = this._getBricks( this.element.children() );
},


reload : function( callback ) {
  this.reloadItems();
  this._init( callback );
},

Anyone see any problem with this?

Upvotes: 1

Fr&#233;d&#233;ric Hamidi
Fr&#233;d&#233;ric Hamidi

Reputation: 263047

You have to pass the new content to Masonry's appended method:

$("#container").append(content).masonry("appended", content);

I updated your fiddle here.

Upvotes: 2

Related Questions