Responsive Masonry jQuery layout example

robflate picture robflate · Jan 28, 2012 · Viewed 18.2k times · Source

Can anyone suggest how this site uses the jQuery Masonry plugin for its responsive, fluid layout?

http://tympanus.net/codrops/collective/collective-2/

Specifically;

The number of columns changes from 3 to 2 to 1 on browser resize which is what you expect from a site using masonry, but what's interesting is the columns also resize to always fill the full width available. Most other Masonry sites I've seen leave gaps to the right of the columns as the number of columns changes (e.g http://masonry.desandro.com/) OR the columns fill the full width but the number fo columns stays the same (http://masonry.desandro.com/demos/fluid.html). Are they dynamically setting the number of columns on browser resize combined with CSS media queries or maybe they're using CSS3 columns?

Thanks.

Answer

some_guy picture some_guy · Feb 11, 2012

This is the Code we are looking at.

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 = 1;
            else if( w_w <= 768 ) n = 2;
            else n = 3;
        },
        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: 400
                    }
                });
            });
            $ctCollContainer.colladjust();
            $ctCollContainer.find('div.ct-coll-item-multi').collslider();
        };
        return { init: init };
    })();
    CollManag.init();
}); 

The Basic idea seems to be to add a columnselector which finds out how many columns can be set. Second step is to use the smartresize event in the function. Third step is to call masonry with the "dynamic" width of columns. Have fun :)