CodeLair scripts and tutorials; click to return to home page

Everything Random!

Utilise the Javascript random functions to display random quotes, images, or a mix!
Last updated: April 15, 2007

Ever wanted to display a random quote or image on your pages? Or perhaps you've got some links to other sites, and you want to put a random one on a page. Well this tutorial will explain how to do all these.

 

The Math library

A Javascript library is a collection of functions with some connection: in this case, they are all number-related. You call a function from a library like so:

Library.function_name(parameters)

Javascript has its own built-in random function, which is part of the Math library. So to call the this function, we use:

Math.random()

This function returns a floating-point number (not a whole number) between 0 and 1, e.g. 0.123456789 or 0.66598474125. Another function we will be using is floor, also from the Math library. This function takes a number as a parameter (in the brackets) and returns the integer part of a number: i.e. the number before the decimal point. For example, if we apply the function to the numbers 3.4567, 27.9545678295 and 150 separately we will get back 3, 27 and 150 respectively.

 

Creating a random number generator

Suppose we want to generate a random whole number (integer) between 0 and 99 inclusive. There are 100 different numbers to choose from here, and Math.random returns a number between 0 and 1, so if we multiply this by 100, we will get a random number between 0 and 100, non-inclusive. However, we want an integer, and so we use Math.floor to round this down to an integer between 0 and 99. Confused yet? Here's the Javascript code; it's actually quite simple.

var rand = Math.floor(Math.random() * 100)

We store the number returned in a variable called rand, so we can use it again later. There is a reason we generated a number between 0 and 99 and not, say, 1 and 100, which will become clear in the next section. But if you wanted to do the latter, all you need to do is add 1 on to the result:

var rand = Math.floor(Math.random() * 100) + 1

And of course to change the range from 1-100 to say 1-50,  just change the 100 in the line above to 50. Simple!

 

Random Quotes

"Finally something useful!" I hear you say. The following script will display a random piece of text at the point where you place it in your document.

View the demo

The full script can be seen at the bottom of the section, but I will explain how it works line-by-line and how to modify it to suit your needs. Start by opening a Javascript section in your HTML document:

<SCRIPT LANGUAGE="JavaScript">

Next we set up some variables. num_quotes is the number of quotes the script will choose from, and we will store the quotes in an array called quotes. If you have not used arrays before, they are simply a list of values or strings (pieces of text) which are stored in one variable and accessed through an index in square brackets. The indexes of arrays always start at 0; an array with 5 elements (as in the example below) will have indexes of 0, 1, 2, 3 and 4.

Here's the next part of the script:

var num_quotes = 5
var quotes = new Array(num_quotes)

quotes[0] = "Why isn't phonetic spelled the way it sounds?"
quotes[1] = "Why do fat chance and slim chance mean the same thing?"
quotes[2] = "Have you ever imagined a world with no hypothetical situations?"
quotes[3] = "If nothing ever sticks to Teflon, how do they make Teflon stick to the pan?"
quotes[4] = "Why is it called a TV \"set\" when you only get one?"

When we make an array we have to say in advance how big it will be: this is what the second line does. The subsequent lines list the quotes we will be able to choose from. Any text can go in between the double quotes, however if you want to include quotation marks in the text somewhere, you must precede them with a backwards slash: \. This is called escaping the character. This can be seen in the final quote.

Finally, we generate a random number, then display the corresponding quote in the array:

var n = Math.floor(Math.random() * num_quotes)
document.write( quotes[n] )
</SCRIPT>

And don't forget to close the script tag! If you want to change the number of quotes, here's what you have to do:

  1. Change the variable num_quotes to however many quotes you want.
  2. Add all the quotes to the array. Use exactly the same syntax, but put the number of each quote in the square brackets, and type the quote between quotation marks in the same way as above. Remember that the quote numbers start at 0 and increase by 1 each time, and the last quote will have an index one less than 'num_quotes'.

Want to add formatting to the quotes? All you have to do is add the HTML code in quotation marks before and after quote[n] in the parentheses of the last line:

document.write( "<b>" + quotes[n] + "</b>" )

The same rules about escaping quotation marks applies here. Also note the + signs which connect each of the text strings together. Here's the full script for random quotes:

<SCRIPT LANGUAGE="JavaScript">
var num_quotes = 5
var quotes = new Array(num_quotes)

quotes[0] = "Why isn't phonetic spelled the way it sounds?"
quotes[1] = "Why do fat chance and slim chance mean the same thing?"
quotes[2] = "Have you ever imagined a world with no hypothetical situations?"
quotes[3] = "If nothing ever sticks to Teflon, how do they make Teflon stick to the pan?"
quotes[4] = "Why is it called a TV \"set\" when you only get one?"

var n = Math.floor(Math.random() * num_quotes)
document.write( quotes[n] )
</SCRIPT>

 

Random Images

This script uses a similar method to above. We use the array to define a list of all the filenames of the images we want to display, and the HTML is taken care of in the last line.

View the demo

<SCRIPT LANGUAGE="JavaScript">
var num_images = 5
var images = new Array(num_images)

images[0] = "star.gif"
images[1] = "gear.gif"
images[2] = "sun.gif"
images[3] = "spiky.gif"
images[4] = "burst.gif"

var n = Math.floor(Math.random() * num_images)
document.write( "<img src=\"" +images[n]+ "\">" )
</SCRIPT>

This should be pretty self-explanatory, and easy to modify for your purposes. We add the image HTML code to the document.write function to display the image.

 

Random anything!

By now you should have a feel for the script and should be able to modify it to suit any purpose. All you need to do is list the things you want to display (remember to change the first variable!), generate a random number, then display the corresponding element in the array with document.write. Inside the quotation marks of each array element you can put any HTML code you want to display: so to display random links with an image, just put in the code required. The script is flexible for any number of random anything!