Phillip Phillop Phillip Phillop - 2 months ago 14
jQuery Question

jquery masonry style grid

I'm trying to build a masonry style layout and position element using jquery. when iterating over the elements, i'm trying to reset the column position once the row has become 3 columns wide but this code isn't working and i don't understand why

var rowPos = 0;

$(document).ready(function(){

$('.box').each(function(ind){

var elementWidth = $(this).width();
var elementHeight = $(this).height();

$(this).css({

left: rowPos +'px'
});


if(rowPos >= elementWidth * 2){
rowPos === 0;

}else{
rowPos += elementWidth;
}

console.log(rowPos);
});

});


this results in 3 columns wide with additional elements stacked on top of the third.

css

body{
font-size: 20px;
}

.container{
position: relative;
}

.box{
width: 33.333%;
position: absolute;
color: #fff;
text-align: center;
box-sizing: border-box;

}
.box span{
margin-top: -1em;
position: relative;
top: 50%;
margin-top: -1em;
}

.box1, .box3, .box6, .box8{

height: 400px;

}

.box2, .box5{
height: 600px;
}
.box4, .box7{
height: 350px;
}

.container div:nth-child(odd){
background: #2a8d6f;

}
.container div:nth-child(even){
background: #5b3eac;

}


markup

<div class="container">
<div class="box box1"><span>box 1</span></div>
<div class="box box2"><span>box 2</span></div>
<div class="box box3"><span>box 3</span></div>
<div class="box box4"><span>box 4</span></div>
<div class="box box5"><span>box 5</span></div>
<div class="box box6"><span>box 6</span></div>
<div class="box box7"><span>box 7</span></div>
<div class="box box8"><span>box 8</span></div>

</div>

Answer

I think it should be

if(rowPos >= elementWidth * 2){
    rowPos = 0; //not rowPos === 0;

}else{
    rowPos += elementWidth;
}