jQuery Masonry layout is breaking when window is resized — fluid seamless photo grid

davecave picture davecave · Mar 6, 2012 · Viewed 9.4k times · Source

I have posted a video explaining my problem. Sorry for the slow frame rate.

When I shrink the window too fast, the Masonry jQuery plugin seems to be too slow to keep up and therefore breaks the layout when the browser is resized too quickly. Some of the items fall below the footer, and it looks obviously wrong.

When I reload the page, as seen in the video, the layout returns to normal.

I think it is a problem is smartresize

Here is the demo page: http://test.davewhitley.com/not-wp/isotope_test/index.php

This page successfully does it: http://tympanus.net/codrops/collective/collective-2/

the javascript:

jQuery(document).ready(function($) {
var CollManag = (function() {
    var $ctCollContainer = $('#ct-coll-container'),
    collCnt = 1,
    init = function() {
        changeColCnt();
        initEvents();
        initPlugins();
    },
    changeColCnt = function() {
        var w_w = $(window).width();
        if( w_w <= 600 ) n = 2;
        else if( w_w <= 768 ) n = 3;
        else n = 4;
    },
    initEvents = function() {
        $(window).on( 'smartresize.CollManag', function( event ) {
            changeColCnt();
        });
    },
    initPlugins = function() {
        $ctCollContainer.imagesLoaded( function(){
            $ctCollContainer.masonry({
                itemSelector : '.ct-coll-item',
                columnWidth : function( containerWidth ) {
                    return containerWidth / n;
                },
                isAnimated : true,
                animationOptions: {
                    duration: 300
                }
            });
        });
        $ctCollContainer.colladjust();
        $ctCollContainer.find('div.ct-coll-item-multi').collslider();
    };
    return { init: init };
})();
CollManag.init();
});

Answer

ktabarez picture ktabarez · Mar 29, 2014

I had the same issue. I used bindResize on windows resize. I found this solution on their website

Masonry Methods

bindResize is at masonry.pkgd

$container.masonry({
    itemSelector: '.container'
});

$(window).resize(function () {
    $container.masonry('bindResize')
});