Randomly position generated divs throughout a header - Javascript Jquery

I have created a header and I need to randomly position div's that resemble stars throughout the header. I have generated 50 of these 'stars' that are span tags with a class of star. CSS turns the star class into somewhat of a star. But, after I have created these 50 spans, I need to randomly position them throughout my header. I have tried generating a random number and assigning it to the class of star but then all the span's happen to have that margin. I need to use margin-top and margin-left with percentages. I have tried assigning the percent to margin-top and margin-left of the div but nothing seems to position them randomly. You can see the demo on codepen. My code:

<div class="header" id="head">
<div class="starholder" id="holdstar">

</div>
<div class="top_nav">
    <i class="fa fa-bars"></i>
</div>
<div class="text text-center">
    <p id="name">Nick <span id="lastname">D</span</p>
</div>
    <div class="mtn1">
    </div>
    <div class="mtn2">
    </div>
    <div class="mtn3">
    </div>

$(document).ready(function() {
//Name hinge
$("#name").click(function() {
    $(".text").addClass("bounce");
    setTimeout(function() {
            $(".text").removeClass("bounce");
    }, 3000);
});


// create stars and place them at random
function createStar() {

    var holder = document.getElementById("holdstar");

    for (var i = 0; i < 50; i++) {
            var percent = Math.floor((Math.random() * 100) + 1);
    var string = percent + "%"

    var percenttwo = Math.floor((Math.random() * 100) + 1);
        var stringtwo = percenttwo + "%";

        var star = document.createElement("span");
        star.className = "star";

$(".star").css({
    "margin-top": string,
    "margin-left": stringtwo
});
        document.getElementById("holdstar").appendChild(star);
    }
};


createStar();

});

I have looked around for possible answers but none that directly affects multiple divs, any help is wanted.

Answers 1

  • I'm not sure what effect you desire exactly, but I can explain why your randomness is not "random" (i.e., why every element has the same margin in your CodePen).

    Instead of passing '.star' as your selector to style the element margins (which selects every star), you should be passing the variable star that you just created:

    $(star).css({
      "margin-top": string,
      "margin-left": stringtwo
    });
    

Related Articles