Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Masonry.js column numbers change on browser width

How is it possible to change the number of columns in Masonry on browser windows width?

Something like this:

@media all and (min-device-width: 320px) and (max-device-width : 480px) { 2 columns }
@media all and (min-device-width : 768px) and (max-device-width : 1024px) { 3 columns }
@media all and (min-width : 1024px) { 4 columns }
$('#content .home').masonry({
    //options
    itemSelector : '.item',
    columnWidth : function(containerWidth) {
        return containerWidth / 2; 
    },
    isAnimated: true
});
like image 323
aegyed Avatar asked May 30 '26 06:05

aegyed


1 Answers

Try something like this:

jQuery(document).ready(function($) {
var CollManag = (function() {
    var $ctCollContainer = $('#grid'),
    collCnt = 1,
    init = function() {
        changeColCnt();
        initEvents();
        initPlugins();
    },
    changeColCnt = function() {
        var w_w = $(window).width();
        if( w_w <= 480 ) n = 1;
        else if( w_w <= 700 ) n = 2;
        else n = 3;
    },
    initEvents = function() {
        $(window).on( 'smartresize.CollManag', function( event ) {
            changeColCnt();
        });
    },
    initPlugins = function() {
        $ctCollContainer.imagesLoaded( function(){
            $ctCollContainer.masonry({
                itemSelector : '.box_item',
                columnWidth : function( containerWidth ) {
                    return containerWidth / n;
                },
                isAnimated : true,
                animationOptions: {
                    duration: 400
                }
            });
        });

    };
    return { init: init };
})();
CollManag.init();
}); 

Or

$( window ).load( function()
{
    var columns    = 3,
        setColumns = function() { columns = $( window ).width() > 700 ? 3 : $( window ).width() > 480 ? 2 : 1 };

    setColumns();
    $( window ).resize( setColumns );

    $( '#grid' ).masonry(
    {
        itemSelector: '.box_item',
        gutterWidth: 0,
        isAnimated: true,
        columnWidth:  function( containerWidth ) { return containerWidth / columns; }
    });
});
like image 177
saintmalo Avatar answered Jun 01 '26 19:06

saintmalo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!