Appending new elements

New elements can be appended to ‘masoned’ containers and then arranged to the layout using the appendedContent option. appendedContent accepts the a jQuery object of the newly appended elements. In this example, each time the button is clicked, new box elements are created and then together made into a jQuery object. This object is first appended to the wrapping container, then the boxes are rearranged with a .masonry() call. Finally, using the callback function, the new boxes are dynamically styled.

In the click function, appendedContent was the only option to specify in the masonry configuration since Masonry saves all previous options. Using appendedContent, the Masonry script saves some processing time as it only rearranges the box(es) inside that appended container.

// cache masonry wrap
var $wall = $('#demo').find('.wrap');

$wall.masonry({
  columnWidth: 100, 
  itemSelector: '.box'
});

$('#append_new_bricks').click(function() {
  var 
    newEls = [],
    elCount = Math.random()*4
  ;
  for (var i=0; i < elCount; i++ ) {
    var 
      colClass = 'col' +  Math.ceil( Math.random()*3 ),
      // create new box
      $box = $( document.createElement('div') )
                .addClass('box ' + colClass).text( randoLoremText() )
    ;
    // add box DOM node to array of new elements
    newEls.push( $box[0] );
  }

  // create jQuery object
  $boxes = $( newEls );

  $wall
    // append new elements
    .append( $boxes )
    // arrange new elements
    .masonry( { appendedContent: $boxes } ,
      // using a callback to style new elements
      function() { 
        $(this).css({background: '#222', color: '#EEE' });
      }    
    )
  ;
}

Sit amet mi ullamcorper vehicula

Phasellus pede arcu, dapibus eu, fermentum et, dapibus sed, urna.

Ut condimentum mi vel tellus. Suspendisse laoreet. Fusce ut est sed dolor gravida convallis. Morbi vitae ante. Vivamus ultrices luctus nunc. Suspendisse et dolor. Etiam dignissim. Proin malesuada adipiscing lacus. Donec metus. Curabitur gravida.

Phasellus pede arcu, dapibus eu, fermentum et, dapibus sed, urna.

Sed ac risus. Phasellus lacinia, magna a ullamcorper laoreet, lectus arcu pulvinar risus, vitae facilisis libero dolor a purus. Sed vel lacus. Mauris nibh felis, adipiscing varius, adipiscing in, lacinia vel, tellus. Suspendisse ac urna. Etiam pellentesque mauris ut lectus. Nunc tellus ante, mattis eget, gravida vitae, ultricies ac, leo. Integer leo pede, ornare a, lacinia eu, vulputate vel, nisl.

Morbi purus libero, faucibus adipiscing, commodo quis, gravida id, est. Sed lectus. Praesent elementum hendrerit tortor. Sed semper lorem at felis.

Fusce accumsan mollis eros. Pellentesque a diam sit amet mi ullamcorper vehicula