Home > database >  How to display random image from folder whenever I refresh the page?
How to display random image from folder whenever I refresh the page?

Time:12-13

I tried many ways to display a different image whenever the page is refreshed, but I have no idea how to make this work... I'm still quite new to this so maybe there's something small that I am missing

window.onload=randomp();

var pic_rand=new Array;

pic_rand[0]=new Image();
pic_rand[0].src="folder/image1.png";

pic_rand[1]=new Image();
pic_rand[1].src="folder/image2.png";

pic_rand[2]=new Image();
pic_rand[2].src="folder/image3.png";

function randomp(){
    var randomNum = Math.floor(Math.random() * pic_rand.length);
    document.getElementById("image1").src = pic_rand[randomNum];
}

CodePudding user response:

You don't need to construct an Image object for each source image URL you have. In fact, you don't need any since you already seem to have one in the DOM. Just make an array of source URLs and choose one by random.

Also, make sure to pass the randomp function to onl oad without calling it.

window.onload = randomp;

var pic_rand = ["folder/image1.png", "folder/image2.png", "folder/image3.png"];

function randomp(){
    var randomNum = Math.floor(Math.random() * pic_rand.length);
    document.getElementById("image1").src = pic_rand[randomNum];
}
  • Related