CodeLair website tutorials, articles & scripts

Everything Random in JavaScript

Published: 29 October 2004   •   Updated: 15 April 2007   •   Tags: javascript

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. This tutorial will explain how to do all these. We’ll utilise the Javascript built-in random functions to display random quotes, images, or a anything you like!

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 (a decimal) 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 each of the numbers 3.4567, 27.9545678295 and 150 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, which should make it clearer:

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 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. 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 quotes = new Array()

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 num_quotes = quotes.length

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.

We end by setting a variable num_quotes to the size of the array using the length property. This means we can add as many quotes as we like without having to change other variables.

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 add more quotes, repeat the last line of quotes using the same syntax, but increase the number in the square brackets by 1.

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, then connect each part with the + symbol:

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

The same rules about escaping quotation marks applies here. Here’s the full script for random quotes:

<script language="JavaScript">
var quotes = new Array()

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 num_quotes = quotes.length
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 demo

<script language="JavaScript">
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 num_images = images.length
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, 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!