I have tried to generate 5 different random numbers in the for loop to generate the 5 images, but the 5 random numbers are generated exactly the same! var numberOfFaces = 5;
var theLeftSide = document.getElementById("leftSide");
for (var i = 0; i < numberOfFaces; i++) {
//create image
var img = document.createElement('img');
img.src = "http://home.cse.ust.hk/~rossiter/mooc/matching_game/smile.png";
var random1 = Math.floor(Math.random() * 500 - (100 * i));
var random2 = Math.floor(Math.random() * 500 - 100 * i);
img.style.top = random1;
img.style.left = random2;
document.body.appendChild(img);
}
It's not that the random numbers aren't random, but to set the css values you'll need a unit as well, like pixels, percentage etc.
img.style.top = random1 + 'px';
img.style.left = random2 + 'px';
And for those CSS values to take effect, the elements have to have a position other than static
img.style.position = 'absolute';
FIDDLE
(Sir check your random number generation statement)
There are some examples on the Mozilla Developer Center page:
/**
* Returns a random number between min (inclusive) and max (exclusive)
*/
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
/**
* Returns a random integer between min (inclusive) and max (inclusive)
* Using Math.round() will give you a non-uniform distribution!
*/
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With