Dynamically Adding HTML Elements to a Masonry Container

The official Masonry documentation doesn’t really cover this well, and all the external examples I found seem to be outdated. I got it working in v3.1.2 via trial and error. Basically, you just have to reload all the items before laying them out. Makes sense once you understand it…

var mediaItemContainer = $( '#container' );
mediaItemContainer.masonry( {
	columnWidth:  '210px',
	itemSelector: '.item'
} );
$( mediaItemContainer ).prepend( '<div class="item">foo</div>' );
$( mediaItemContainer ).masonry( 'reloadItems' );
$( mediaItemContainer ).masonry( 'layout' );

34 thoughts on “Dynamically Adding HTML Elements to a Masonry Container

  1. Gotta say… this helped me tremendously. So happy you did this tutorial and thanks for saving me a day of my life beating my head on code.

Leave a Reply

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