Mona Coder
Mona Coder

Reputation: 6316

Adding style to dynamically generated divs

I am working on this demo. Why am I not able to add margin to dynamically generated divs?

jQuery(function () {
    var rnd1 = Math.ceil(Math.random() * 450);
    var rnd2 = Math.ceil(Math.random() * 450);
    for (var i = 0; i < 6; i++) {
        $('.wrapper').append('<div class="box"></div>');
        //        $('.box').css({"left": rnd1,"top": rnd2});
    }
    $(".box").each(function () {
        $(this).css({
            "left": rnd1,
            "top": rnd2
        });
    });

As you can see I tried both:

$('.box').css({"left": rnd1,"top": rnd2});

inside the loop and using .each() as:

 $(".box").each(function () {
        $(this).css({
            "left": rnd1,
            "top": rnd2
        });
    });

out of the loop but apparently they are not doing the job!

Upvotes: 0

Views: 109

Answers (1)

adeneo
adeneo

Reputation: 318352

Because you're not adding margin, you're setting the top and left position, and that only works if the element doesn't have a static position

$(this).css({"left": rnd1,"top": rnd2, position: 'relative'});

or you could actually add margin instead

$(this).css({"margin-left": rnd1, "margin-top": rnd2});

As a sidenote, you can add the styles when you're creating the elements, the second loop is uneccessary

for (var i = 0; i < 6; i++) {
    $('.wrapper').append(
        $('<div />', {
            'class' : 'box',
            css : {
                marginLeft : rnd1,
                marginTop  : rnd2
            }
        })
    );
}

Upvotes: 1

Related Questions