Dr. Mark Humphrys

School of Computing. Dublin City University.

Online coding site: Ancient Brain

coders   JavaScript worlds

Search:

Free AI exercises


Lab - Javascript



Random image each time page is loaded

  

Start code

  

Recipe

  1. "i" is from 0 to 1. How do you get a random number from 0 to 10? When you have worked out what to do to "i" to get that, document.write the new random number from 0 to 10.

  2. The new "i" is a real number from 0 to 10 (excludes 10). How do you get a random integer from 0 to 9 (includes all of those in equal proportions)? OK, I will help. See Math.floor. Now document.write the new random integer from 0 to 9.
    Q. Why was it important to exclude 10 itself?

  3. The new "i" is a random integer from 0 to 9. Now construct the URL of the image corresponding to that.
  4. Now document.write an img tag into the page with src equal to that URL.
  5. Now every time you load the page it has a random image.





Change it to an Array

Re-code the above using an Array of image URL strings:
 var thearray = [ 
	"https://humphrysfamilytree.com/Icons/logo.rotate.2.jpg", 
	"https://upload.wikimedia.org/wikipedia/commons/thumb/f/f5/Gioconda.jpg/400px-Gioconda.jpg",
	"https://humphryscomputing.com/3d/Images/earth.1.big.jpg"
	];

 var i = Math.floor ( Math.random() * thearray.length );	// returns random 0 to (thearray.length - 1)	 

 // display i to check it 

 var url = ....   // get the ith element of the array (see Array docs)

 ....   // display the image inline      




ancientbrain.com      w2mind.org      humphrysfamilytree.com

On the Internet since 1987.      New 250 G VPS server.

Note: Links on this site to user-generated content like Wikipedia are highlighted in red as possibly unreliable. My view is that such links are highly useful but flawed.