mercredi 20 janvier 2021

Generate a random image on page load

I am trying to pull a random image on load with a JavaScript function on my site and set it as the body background-image.

I’ve been searching and trying to piece together a solution but have been unsuccessful.

Here is what I have,

function chatimgset() {  
//declare an array
var randomImage = new Array();  
  
//insert the URL of images in array  
randomImage[0] = "image.png";  
randomImage[1] = "image 2.png";  
randomImage[2] = "image 3.png";  
randomImage[3] = "image 4.png ";  
randomImage[4] = "image 5.png";    
  
//generate a number 
var number = Math.floor(Math.random()*randomImage.length);  
  
//return the images generated by number 
return  
  document.getElementsByTagName("body")[0].setAttribute("background-image", "'"+randomImage[number]+"'");
}

Where did I go wrong on this?

Thanks!




Aucun commentaire:

Enregistrer un commentaire