I’ve researched extensively on this but still havent been able to make Masonry work with WordPress and Infinite Scroll. I’m pretty new with to jQuery so I’m not sure what I’m missing.
I’m working on a WordPress theme using Masonry and Infinite Scroll. Masonry works fine when the page is first loaded, but when I start scrolling, the new appended items do not follow the masonry layout. (see images below)
New items appended – Masonry breaks
How do I make the appended items load properly in a masonry layout?
Here is my code.
Scripts used
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-infinitescroll/2.0b2.120519/jquery.infinitescroll.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/masonry/3.1.2/masonry.pkgd.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery.imagesloaded/3.0.4/jquery.imagesloaded.min.js"></script>
HTML
<main id="grid">
<div class="grid-sizer"></div>
<div class="grid-item"><article>...</article></div>
<div class="grid-item"><article>...</article></div>
<div class="grid-item"><article>...</article></div>
<div class="grid-item"><article>...</article></div>
<div class="grid-item"><article>...</article></div>
...
</main>
CSS
.grid-sizer,
.grid-item { width: 20%; }
jQuery script
/**
* Infinite Scroll + Masonry + ImagesLoaded
*/
(function() {
// Main content container
var $container = $('#grid');
// Masonry + ImagesLoaded
$container.imagesLoaded(function(){
$container.masonry({
itemSelector: '.grid-item',
columnWidth: '.grid-sizer',
percentPosition: true
});
});
// Infinite Scroll
container.infinitescroll({
// selector for the paged navigation (it will be hidden)
navSelector : ".navigation",
// selector for the NEXT link (to page 2)
nextSelector : ".nav-previous a",
// selector for all items you'll retrieve
itemSelector : ".grid-item",
// finished message
loading: {
finishedMsg: 'No more pages to load.'
}
},
// Trigger Masonry as a callback
function( newElements ) {
// hide new items while they are loading
var $newElems = $( newElements ).css({ opacity: 0 });
// ensure that images load before adding to masonry layout
$newElems.imagesLoaded(function(){
// show elems now they're ready
$newElems.animate({ opacity: 1 });
$container.masonry( 'appended', $newElems, true );
});
});
/**
* OPTIONAL!
* Load new pages by clicking a link
*/
// Pause Infinite Scroll
$(window).unbind('.infscr');
// Resume Infinite Scroll
$('.nav-previous a').click(function(){
$container.infinitescroll('retrieve');
return false;
});
})();
Appreciate the help. Thanks in advance!