blocks

stackOverflow question

HTML

<div id="wrapper">
    
<div class="block">
    <h2>I'm block 1</h2>
</div>

<div class="block">
    <h2>I'm block 2</h2>
</div>

<div class="block">
    <h2>I'm block 3</h2>
</div>

<div class="block">
    <h2>I'm block 4</h2>
</div>

</div>

CSS

.block {
    width: 200px;
    height: 100px;
    margin: 20px;
    text-align: center;
    line-height: 100px;
    cursor: pointer;
    position: absolute;
}
.block:nth-child(1) {
    background: green;
}
.block:nth-child(2) {
    background: red;
}
.block:nth-child(3) {
    background: orange;
}
.block:nth-child(4) {
    background: pink;
}

JavaScript

var reposition = function() {
    wrapper = $("#wrapper");
    console.log(wrapper.innerWidth());
    pLeft = 0;
    pTop = 0;
    $(".block").each(function(){
        $(this).stop(0,0).animate({
          'top' : pTop + 'px',
          'left' : pLeft + 'px'
        });
        pLeft += $(this).width();
        console.log(pLeft);
        if(pLeft + $(this).next().width() >= wrapper.innerWidth()) {
           pLeft = 0;
           pTop += $(this).height();
        }
    });    
};

$(window).resize(function() {
    reposition();
});

$(document).ready(function() {
    reposition();
    
    $(".block").click(function() {
        $(this).siblings().slideToggle('slow');
        if(!$(this).data('active')){                
            $(this).data('left', $(this).position().left);
            $(this).data('top', $(this).position().top);        
            $(this).animate({
                top:0,
                left:0
            },'slow');
            $(this).data('active',true);
        }else{
            $(this).animate({
                top:$(this).data('top'),
                left:$(this).data('left')
            },'slow');
            $(this).data('active',false);
        }
    });

});