Masonry style arrangement using jQuery

by Sree K

HTML

<div class="container">
    <div class="item">1.</div>
    <div class="item wv">2.</div>
    <div class="item w">3.</div>
    <div class="item wv">4.</div>
    <div class="item wv">5.</div>
    <div class="item">6.</div>
    <div class="item w">7.</div>
</div>

CSS

/* --- CSS --- */
 .item {
    display:block;
    width:80px;
    margin:5px;
    background:grey;
    min-height:30px;
    float:left;
    position:relative;
    border:1px solid green;
}
/* classes for variation in height*/
 .w {
    min-height:40px;
}
.wv {
    min-height:50px;
}

JavaScript

<!-- JavaScript -->
$(function () {
    // for full Tutorial, please visit http://curiohub.blogspot.in/2014/04/simple-jquery-script-to-arrange-elements-in-vertical-space.html
    // change width of Resutls window to see effect.
    $('.item').css('position', 'absolute');
    rearrange();
    $(window).resize(function () {
        rearrange();
    });



    function rearrange() {


        var ti = $('.item').length; //total number of items
        var cw = $('.item').first().outerWidth(true); //column width
        var mr = parseInt($('.item').first().css("marginLeft"), 10); //margin left
        var mt = parseInt($('.item').first().css("marginTop"), 10); //margin top
        var contw = $('.container').width(); //container width

        if (contw < cw) {
            return; // if column width is greater then available space.
        }

        var pl = Math.floor(contw / cw); // no. of items per line

        for (i = 1; i <= ti; i++) {
            var upElement = (i - pl);
            var left = (i % pl);
            var leftv = 0;
            if (left == 0) {
                leftv = ((pl - 1) * cw) + mr;
            } else {
                leftv = ((left - 1) * cw) + mr;
            }

            if (upElement > 0) {
                var upELem = $('.item:nth-child(' + upElement + ')');
                var upTop = upELem.position().top;
                var upH = upELem.outerHeight(true);

                $('.item:nth-child(' + i + ')').css({
                    top: (upTop + upH),
                    left: leftv
                });

            } else {
                $('.item:nth-child(' + i + ')').css({
                    top: mt,
                    left: leftv
                });
            }
        }

    }
})();