vendredi 25 mai 2018

Spawn blocks at random locations

I'm trying to create elements in random locations on the screen but I have run into some trouble. Creating the elements works but when I try to make them have random locations, nothing happens. Thanks for the help in advance.

Here's my code:

var newObject = document.createElement("DIV");
newObject.setAttribute("class", "object");
newObject.setAttribute("id", "powerup");
document.body.appendChild(newObject);
var powerup = document.getElementById("powerup");
var object = document.getElementsByClassName("object");
for (i = 0; i < object.length; i++) {
object[i].style.top = Math.floor(Math.random() * window.innerHeight) + 50 + "px";
object[i].style.left = Math.floor(Math.random() * window.innerWidth) + 50 + "px";
}

function createObject() {
var newObject = document.createElement("DIV");
newObject.setAttribute("class", "object");
newObject.setAttribute("id", "powerup");
document.body.appendChild(newObject);
for (i = 0; i < object.length; i++) {
object[i].style.top = Math.floor(Math.random() * window.innerHeight) + 50 + "px";
object[i].style.left = Math.floor(Math.random() * window.innerWidth) + 50 + "px";
}
}
html, body {
height: 100%;
width: 100%;
margin: 0;
}
#powerup {
background: red;
height: 10px;
width: 10px;
}
<body>
<button onclick="createObject()">Create a Block</button>
</body>



Aucun commentaire:

Enregistrer un commentaire