rekalar rekalar - 1 year ago 77
Javascript Question

JavaScript Get a Random Image in a for loop

So I created a for loop which creates (determining on a textfield) a number of images.

E.g. I type "23" in the textfield and on a button click it displays 23 images randomly placed on the screen.

for(i=0; i < box2; i++) {

this.y = Math.floor(Math.random() * 100) + 1;
this.x = Math.floor(Math.random() * 100) + 1;

this.img = document.createElement("img");
this.img.src = sourceArray[num];
this.img.setAttribute("height", "100px"); = "absolute"; = this.y + "vh"; = this.x + "vw";
this.img.addEventListener("click", Remove);



I also already have an array to pick 1 out of 3 random images which works fine, but it will only display 1 of the 3 for all images. When I reload it will pick another one from the list.

var sourceArray = ["strand.jpg","weg.jpg","haengematte.jpg"];
var num = Math.floor(Math.random() * 3);

How can I change it that it displays all 3 images randomly?

e.g. I type "12", click the button and get 12 images randomly from the given 3 sources.

Answer Source

You should put the

var num = Math.floor(Math.random() * 3);

line inside the loop.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download