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. Thanks for the tip.
    Furthermore, if you’re using Masonry via Isotope use:

    $( mediaItemContainer ).isotope( ‘reloadItems’ ).isotope({ sortBy: ‘original-order’ });

    Instead of:

    $( mediaItemContainer ).masonry( ‘reloadItems’ );
    $( mediaItemContainer ).masonry( ‘layout’ );

  2. Really thanks!!!!
    While using Masonry and append item, extra whitespace will be occurred at the top of those items, just adding the reload and layout and it solved!!

    Just keep searching for some time, trying to add some more keyword here and benefit for more people.

  3. Reload masonry after refresh views in drupal 7 : ajax

    (function ($) {
    Drupal.behaviors.myViewsRefresh = {
    attach: function( context , settings) {

    var viewName = ‘page_agenda’;

    // View is Ajax enabled,
    // and is available as a property of the Drupal object
    // like so…
    var instances = settings.views.ajaxViews;
    var targetedView;

    // iterate thru the various
    // views instances name to find your views
    $.each( instances , function getInstance( index, element){
    if(element.view_name == viewName ){

    var mediaItemContainer = jQuery( ‘.view-page-agenda .view-content’ );
    mediaItemContainer.masonry( {
    columnWidth: ”,
    itemSelector: ‘.views-row’
    } );

    jQuery( mediaItemContainer ).masonry( ‘reloadItems’ );
    jQuery( mediaItemContainer ).masonry( ‘layout’ );

    }
    });

    }
    }
    })(jQuery);

  4. Hi, thanks for this. When I use $posts_container.masonry(‘reloadItems’); though the items all move back to the left hand side and get moved back to their position, which does not happen for me on page load. Are you able to help? Does this happen to you too?

Leave a Reply

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