Issue on Adding Style to Dynamically Generated Divs

Problem

Can you please take a look at This Demo and let me know why I am 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! Thanks

Problem courtesy of: Mona Coder

Solution

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
            }
        })
    );
}
Solution courtesy of: adeneo

Discussion

There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.