Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate 5 different random numbers?

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);

}
like image 423
Computerlucaworld Avatar asked Jan 08 '23 07:01

Computerlucaworld


2 Answers

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

like image 55
adeneo Avatar answered Jan 15 '23 03:01

adeneo


(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;
}
like image 42
Brijesh Kumar Avatar answered Jan 15 '23 03:01

Brijesh Kumar