isotope's 'appended' feature
dynamically adding and laying out a new block of images to an isotope/masonry container
by jack gold
HTML
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery.isotope/2.0.0/isotope.pkgd.min.js"></script>
<div class="img-gallery">
<div class="image-grid">
<div class="grid-item grid-col-sm">
<img class="img-responsive" src="http://placehold.it/50x30" alt="" />
</div>
<div class="grid-item grid-col-sm">
<img class="img-responsive" src="http://placehold.it/50x50" alt="" />
</div>
</div>
</div>
<button class="gallery-btn">Click me</button>
SCSS
.img-gallery { max-width: 300px; min-height: 300px; }
.grid-item { margin: 5px; }
JavaScript
$(document).ready(function () {
var srcs = [
'http://placehold.it/50x25/0cd',
'http://placehold.it/25x25/0cd',
'http://placehold.it/50x25/0cd',
'http://placehold.it/25x25/0cd',
'http://placehold.it/50x25/0cd',
'http://placehold.it/25x25/0cd', 'http://placehold.it/50x25/0cd',
'http://placehold.it/25x25/0cd', 'http://placehold.it/50x25/0cd',
'http://placehold.it/25x25/0cd', 'http://placehold.it/50x25/0cd',
'http://placehold.it/25x25/0cd', 'http://placehold.it/50x25/0cd',
'http://placehold.it/25x25/0cd',
];
var $container = $('.img-gallery');
$container.isotope({
layout: 'masonry'
});
$('.gallery-btn').on('click', function (e) {
e.preventDefault();
var $elems = makeImage(srcs[0])
.add(makeImage(srcs[1]));
$container.append($elems)
.isotope('appended', $elems);
});
});
// interestingly, defining makeImage way down here, after the rest,
// makes things execute in the correct order
// otherwise we sometimes hit errors depending on timing/latency
// or get doubled-up images
function makeImage(src) {
var $img = $('<div class="grid-item grid-col-sm"><img class="img-responsive" src="' + src + '"></div>');
return $img;
}