I'm trying to make jQuery append a div to the body of my document multiple times, but for some reason its only appending one item and I'm guessing its the last item in the loop.
$(function(){
var howManyParticles = 11;
var bodyWidth = $(document).width();
var randomSpawn = Math.floor(Math.random() * bodyWidth) + 1;
var particleStyle = "background: lightgray;width: 10px;height: 10px;min-height: 10px;min-width: 10px;position: fixed;bottom: 0;left:" + randomSpawn + ";";
var particle = $("<div class='particle' style='"+ particleStyle +"'> </div>");
function spawnParticles(){
for(var i = 0; i <= howManyParticles; i++)
{
$('body').append(particle);
console.log('spawned');
}
}
spawnParticles();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
This only spawns 1 item to the window, how do i make it so it spawns as many items as i <= howManyParticles
is going to be?
EDIT: My Final Code
I forgot that i need to put the math.random
function within the loop to give a different horizontal value to each different particle that was spawned!
$(function(){
var howManyParticles = 11;
var bodyWidth = $(document).width();
function spawnParticles(){
for(var i = 0; i <= howManyParticles; i++)
{
var randomSpawn = Math.floor(Math.random() * bodyWidth) + 1;
var particleStyle = "background: lightgray;width: 10px;height: 10px;min-height: 10px;min-width: 10px;position: fixed;bottom: 0;left:" + randomSpawn + ";";
var particle = $("<div class='particle' style='"+ particleStyle +"'> </div>");
$('body').append(particle);
}
}
spawnParticles();
});