Search code examples
jquerycss-positionpositioning

Add position on loop object with jquery


I have create jquery code to create loop object and I have problem when I want to add top position value. so the idea is to set top value in each loop object so the object will sit in center of each rows.

here is the code :

var $dna = $("<div class='dna'></div>");
var n= $('.box').length / 3;
for(var i = 0; i < n; i++){
$dna.clone().appendTo('.entry');
}
var bx = $('.boxWrap').height()/$('.box').height();
$(".entry .dna").each(function(i) {
$(this).addClass("pattern-" + (i+1)).css({top: bx+"%"});
});

JSfiddle link

Thanks


Solution

  • You need to increment the top: x value with each "row" iteration:

    var $dna = $("<div class='dna'></div>");
    var n= $('.box').length / 3;
    var boxHeight = $('.box').height();
    var topPos = 0;
    for(var i = 0; i < n; i++){
        $dna.clone().css('top',topPos).appendTo('.entry');
        topPos += boxHeight;
    }
    

    You can adjust the height values to get the bar to position where you need it.

    Fiddle