Skip to content Skip to sidebar Skip to footer

Looping Using Position Absolute To Form 9 Boxes

1 2 3 4 5 6 7 8 9 I want to achieve above boxes position using absolute positioning and looping in js. But I'm stuck at starting a second line. http://jsfiddle.net/k554x7vs/ var l

Solution 1:

You need to increment top also

var left = 0,
    top = 0;
for (var i = 1; i <= 10; i++) {
    $('<div class="box" id=box' + i + '></div>').appendTo('#holder');
    $('#box' + i).css({
        'left': left,
        top: top
    });
    left += 60;
    if (i % 3 == 0) {//need to increment top also need to use the modulus operator since you want to reset/increment after each 3rd element
        left = 0;
        top += 70;
    }
}

Demo: Fiddle

Solution 2:

The solution is pretty simple. It's a bit hard to explain what I changed, but this works:

var left = 0;
for (var i = 0; i <= 10; i++) {

    $('<div class="box" id=box' + i + '></div>').appendTo('#holder');

    if (i % 3 == 0) {

        //2nd line and so on..
        left = 0;



    }
        $('#box' + i).css({
            top: (i - i % 3) / 3 * 70
        })


    $('#box' + i).css({
        'left': left
    });

    left += 60;
}

Solution 3:

Try

var arr = [1,2,3,4,5,6,7,8,9]
, n = -1;

$.map(arr, function(val, key) {
    var box = $(".box"),
    height = box.height() + 20,
    width = box.width() + 20,
    len = box.length;
    $("<div>", {
        "class":"box",
        "id":"box" + key,
        "css": {
            "left": key < 3 
                    ? (len * width)
                    : box.eq(++n).css("left"),

            "top": key < 3 
                   ? 0 
                   : key < 6
                     ? height 
                     : (2 * height)
        }
    }).appendTo("#holder")
});

http://jsfiddle.net/k554x7vs/6/

Post a Comment for "Looping Using Position Absolute To Form 9 Boxes"