Javascript: Display random images on your site

Who I am
Joel Fulleda
Author and references

How to display a different image every time the web page is loaded?

With Javascript it is definitely very simple. Let's start with an already working script to then explain how it works.

img = new Array() img[0] = 'foto1.jpg" width="" height="" border=""'; img[1] = 'foto2.jpg" width="" height="" border=""'; img[2] = 'foto3.jpg" width="" height="" border=""'; ran = Math.floor(3 * Math.random()); document.write("");

Let's try to understand together how the script works. First we define the img variable as a vector.

img = new Array()

Then we assign the name of a different image to the first three elements (foto1.jpg, foto2.jpg,…). The contents of the three elements are three different string-values ​​in which the main parameters of the tag are inserted through which an image is displayed in Html.

img[0] = ‘foto1.jpg” width=”” height=”” border=””‘;

Once the vector is defined and the string values ​​assigned, the script executes the Math.random function to generate a random number from 0 to 0.999. Multiplying this random value by the constant number 3 we get a random number from 0 to 2. The result of this mathematical expression is finally rounded up using the Math.floor function. In this way we get a random whole number (without a comma). The variable ran will therefore assume the number 0, the number 1 or the number 2 as its value every time the web page is reloaded.

ran = Math.floor(3 * Math.random());

To conclude the script, let's see how to use this random value to display one image rather than another. The tag is displayed in the last statement together with the element of the variable img [] relative to the random number (0, 1 or 2) assumed by the variable ran.

document.write (“");

To give a practical example, if the random number of the ran variable were equal to 1, the script will take into consideration the parameters contained in the string variable img [1], publishing the image foto2.jpg on the screen.

add a comment of Javascript: Display random images on your site
Comment sent successfully! We will review it in the next few hours.