HomePage | Optical Illusions | War Stories | QBasic | Dads Navy Days | Bristol | Bristol, USA | Bristol, Canada | Terre Haute | Miscellany | Web Stuff | About Ray | Site Map | Site Search | Messages | Credits | Links | Web Rings

Web Stuff | Audio | Basics | Browser | Code Tips | Design | Fonts | Forms | Frames (Page 1), (Page 2) | Images (Page 1), (Page 2) | Links | Random | Redirection | Sound | Video | Search Engines | Lycos UK | Home Server (Page 1), (Page 2), (Page 3)

When copying the code from these pages remember to paste them first into a text only editor such as Notepad and then copy and paste from there into your webpage. This is so that all the text formatting codes can be removed from the copied text. Remember that your HTML editor must be in code or HTML view when you paste the code into it. If you are using a template driven HTML editor then the code must be pasted into an HTML and not a text box. JavaScript must be enabled in your browser for the effects generated by it to be seen. The code on this page was tested in IE 6.0.29; Mozilla 1.7.3; Netscape 7.2 and Opera 7.54

Random Numbers

Random Quotes

Random Multi-line Quotes

Random Images

Random Background Image

Random Background Colour

Random Links

JavaScript Random Numbers

The basic method is to use the Math.random() function. All this does is to create a number between 0 and 1.

When random numbers are used they are usually required to fall between a range of numbers. This can be done by using (Math.random() * (Max - Min)) + Min

Suppose a random number between 3 and 12 is needed. The code would be (Math.random()*(12-3))+3 or, more simply (Math.random()*9)+3

But, only the whole numbers are usually needed. For this the Math.round function can be used. Using this, if the fractional part is less than .5 then the number is round down, if greater, it is rounded up. The code now becomes Math.round((Math.random() * (Max - Min)) + Min)

Again, for a random number between 3 and 12, the code would be Math.round((Math.random()*(12-3))+3) or, more simply Math.round((Math.random()*9)+3)

Well, that's great, but what can random numbers be used for? The answer is, anything you like!

Arrays

The usual use for random numbers on web pages is to add some sort of spontaneity, that is, to provide the visitor with some changing content whenever they visit the page or take some action. This is usually done in conjunction with an array that holds various information. Arrays are simply a set of variables that have the same name. Each part of information in the array can be referenced by using its index number. The index numbers begin with 0. Being able to reference information using a number is one of the greatest time savers for programmers.

There are several ways you can set up and populate an array. JavaScript arrays are dynamic in that you don't have to define how many items there are in the array when you first declare it. For example, to declare are array with 6 items you can use var array_name = new Array(6); or you simply use var aquote = new Array; and add 6 items to it. The index for both arrays run from 0 to 5.

The advantage of not declaring a fixed length array is that you can use array_name.length to find how many items are in the array. With a fixed length array array_name.length will always give the number of items you originally specified, even though some of them may be empty.

If array_name.length is used then instead of Math.round, Math.floor must be used. This is because of the different ways these functions round numbers. If array_name.length is used and returns a value of 6 (array index is 0 to 5) then using Math.round the random numbers produced will be in the range 0 to 6. The array index 6 doesn't exist, and an error will result. Using Math.floor corrects this as Math.floor rounds numbers downwards or, more accurately, just truncates the decimal fraction. This gives the correct range of, in this example 0 to 5.

Arrays can also be multi-dimensional, that is, an array element may itself be an array. One way of defining a multi-dimensional array is by using...

var variable_name = new Array(new Array(), new Array(), new Array());

The code produces an array of three elements, each element is itself an array. This is used in the section on multi-line quotes.

You can read more about arrays and how they are used at HTMLGoodies, W3Schools and WebReference

There's a nice explanation on JavaScript multi-dimensional arrays at Evolt

Random Quotes

You can use an array of quotations and a random number generator to display one of them. The quote below is from Douglas Adams, who wrote the magnificent "Hitchhiker's Guide to the Galaxy". A new quote will appear whenever the page is loaded or refreshed.

The code isn't too hard to understand. In the HEAD section of the page place the function to generate the array and random number.

<script language="javascript">
<!-- Hide the script from old browsers
function adamsquote(){
//Define and populate the array
var aquote = new Array;
aquote[0]="\"Very deep, you should send that in to the 'Reader's Digest'. They've got a page for people like you.\"";
aquote[1]="\"This must be Thursday, I never could get the hang of Thursdays.\"";
aquote[2]="\"It was on display in the bottom of a locked filing cabinet stuck in a disused lavatory.\""
aquote[3]="\"This is obviously some strange usage of the word 'safe' that I wasn't previously aware of.";
aquote[4]="\"The best way to get a drink out of a Vogon is to stick your finger down his throat.\"";
aquote[5]="\"If there's anything more important than my ego around, I want it caught and shot now.\"";
aquote[6]="\"The Universe will explode later for your pleasure.\"";
aquote[7]="\"You go to pieces so fast people get hit by the shrapnel.\"";
aquote[8]="\"Anyone who is capable of getting themselves made President should on no account be allowed to do the job.\"";
aquote[9]="\"I think you ought to know that I'm feeling very depressed.\"";
aquote[10]="\"It is not the fall that kills you. It's the sudden stop at the end.\"";
aquote[11]="\"To design something completely foolproof is to underestimate the ingenuity of complete fools.\"";
aquote[12]="\"It's no coincidence that in no known language does the phrase 'As pretty as an airport' appear.\"";

//Generate a random number then print the quote from that array index
rdmQuote = Math.floor(Math.random()*aquote.length);
document.write(aquote[rdmQuote]);
}
-->
</script>

The function must have a name, in this case I used adamsquote.

The line var aquote = new Array; defines a new array named aquote

The following lines eg aquote[6]="\"The Universe will explode later for your pleasure.\""; populates the array. The index numbers are the numbers between the []'s. Notice the \" in the lines, this is an instruction to print the quotation marks.

Because the array index starts at 0, the Math.round((Math.random() * (Max - Min)) + Min); need not be used and can be simplified to Math.floor(Math.random()*aquote.length);

The variable rdmQuote holds the random number generated and is used by the document.write(aquote[rdmQuote]); statement to find and print the appropriate array index.

In the BODY section of the page, where you want the quote to appear put

<p align="center"><font size="4" color="#FF0000">
<script language="javascript">
adamsquote();
</script>
</font></p>

All this does is "call" the JavaScript function that is in the HEAD section of the page. This in turn, generates the array and random number, then prints the selected array index.

Random Multi-Line Quotes

This method using a multi-dimensional array to display multi-line quotes, or even poems on a web page. The way this is arranged is to make a plain text JS file that contains the following...

// Define the poems
// There are 3 poems in this example so need 3 new arrays inside the main one.
// The poem titles are kept in the same arrays as the poems

var poems = new Array(new Array(), new Array(), new Array());

// Add the poem lines to the array
// NOTE Arrays start at 0

poems[0][0]= "Title - Poem 1" + "<br>";
poems[0][1]= "poem1, line 1";
poems[0][2]= "poem1, line 2";
poems[0][3]= "poem1, line 3";
poems[0][4]= "poem1, line 4";
poems[0][5]= "poem1, line 5";
poems[0][6]= "poem1, line 6";
poems[0][7]= "poem1, line 7";
poems[0][8]= "poem1, line 8";

poems[1][0]= "Title - Poem 2" + "<br>";
poems[1][1]= "poem2, line 1";
poems[1][2]= "poem2, line 2";
poems[1][3]= "poem2, line 3";
poems[1][4]= "poem2, line 4";
poems[1][5]= "poem2, line 5";
poems[1][6]= "poem2, line 6";
poems[1][7]= "poem2, line 7";
poems[1][8]= "poem2, line 8";
poems[1][9]= "poem2, line 9";

poems[2][0]= "Title - Poem 3" + "<br>";
poems[2][1]= "poem3, line 1";
poems[2][2]= "poem3, line 2";
poems[2][3]= "poem3, line 3";
poems[2][4]= "poem3, line 4";
poems[2][5]= "poem3, line 5";
poems[2][6]= "poem3, line 6";
poems[2][7]= "poem3, line 7";
poems[2][8]= "poem3, line 8";
poems[2][9]= "poem3, line 9";
poems[2][10]= "poem3, line 10";

// Define the variables
// NOTE - There are 3 poems, but need one less than this in the PoemNum equation
// If you use 4 poems then change the 2 for a 3 and so on.

var count=0;
var poemNum=Math.round(Math.random() * 2);

// Write the poems to the HTML page
for (count=0;count<poems[poemNum].length;count++){
document.write(poems[poemNum][count] + "<br>");
}

I've called this file poems.js

Where you want the lines to appear place the following code in the BODY section of your page, where you want them to appear...

<blockquote><font size="4" color="#0000FF">
<script language="JavaScript" type="text/javascript" src="poems.js"></script>
</font></blockquote>

This will give...

Because writing the JS file can get a bit tedious, especially if you're using lots of long texts, I've written a small Visual Basic Windows program, bipta.exe, to make the task a little easier. The program will take text files and produce the JS file along with a line of code you can paste directly into your HTML page and also a simple HTML page to demonstrate the JS in action.

Download pibta_install.zip - includes sample files (3.5Mb)

Download pibta_source.zip - just the VB Net source code (40kb)

The program itself isn't that big but the installation files are enormous. not only that, but as the program was written in Visual Basic .NET, you may also need to download the .NET Framework, which is another 23.5Mb.

You're more than welcome to play with the code, but if you use part of it for your own program please remember where you got it from and at least leave my name and link to my site in it. If you can think of improvements to the program, I can think of a few myself now the basic program is finished, then just email me at brisray@yahoo.co.uk

Random Images

You can display random images in much the same way as you can quotes. In the HEAD section of the page place the function to generate the array and random number.

<script language="javascript">
<!-- Hide the script from old browsers
function showimage(){
//Define and populate the array
var images = new Array;
images[0]="bkg89.jpg";
images[1]="tile079.jpg";
images[2]="tiedye.gif";

//Generate a random number then display the image from that array index
rdmImage = Math.floor(Math.random()*images.length);
document.write('<img border="0" src="' + images[rdmImage] + '"width="100" height="100">');
}
-->
</script>

In the BODY section of the page, where you want the image to appear put

<p align="center">
<script language="javascript">
showimage();
</script>
</p>

You can adapt the code to display the image to produce a random background for your page. This is demonstrated on rdmbgimg.htm. You can also adapt the code to produce a random background colour. This is demonstrated on rdmbgclr.htm

Random Page Background Image

The code is just a minor reworking of the code above and involves putting the following code in the HEAD section of the page...

<script language="javascript">
<!-- Hide the script from old browsers
function showimage(){
//Define and populate the array
var images = new Array;
images[0]="bkg89.jpg";
images[1]="tile079.jpg";
images[2]="tiedye.gif";
images[3]="back1.jpg";
//Generate a random number then display the image from that array index
rdmImage = Math.floor(Math.random()*images.length);
document.body.style.backgroundImage = 'url(' + images[rdmImage] + ')';
}
-->
</script>

and rewriting the BODY tag of the page to read...

<body onload=showimage()>

This code is demonstrated on rdmbgimg.htm

Random Page Background Colour

The code is just a minor reworking of the code above and involves putting the following code in the HEAD section of the page...

<script language="javascript">
<!-- Hide the script from old browsers
function clrChange(){
//Define and populate the array
var hexNum = new Array("0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F");
//Generate 6 random numbers, and add that array index to rdmHexClr
for (cnt=1;cnt<7;cnt++){
rdmNum=Math.floor(Math.random()*hexNum.length);
rdmHexClr = rdmHexClr + hexNum[rdmNum];
}
rdmHexClr = "#" + rdmHexClr;
document.bgColor=rdmHexClr;
}
-->
</script>

Change the BODY tag to read...

<body onload=clrChange()>

This code is demonstrated on rdmbgclr.htm.

To use only the "web-safe" colours, the code in the head section should be...

<script language="javascript">
<!-- Hide the script from old browsers
function clrChange(){
//Define and populate the array
var hexNum = new Array("00","33","66","99","CC","FF");
//Generate 3 random numbers, and add that array index to rdmHexClr
for (cnt=1;cnt<4;cnt++){
rdmNum=Math.floor(Math.random()*hexNum.length);
rdmHexClr = rdmHexClr + hexNum[rdmNum];
}
rdmHexClr = "#" + rdmHexClr;
document.bgColor=rdmHexClr;
}
-->
</script>

The above code is a little different to the others. Colours for web pages are given as 6 digit hexadecimal (normally just referred to as "Hex") numbers. These are numbers to Base 16 - it's do with the way computers handle numbers. In the RGB way of doing things, the first two digits are red, the middle two green and the last two blue. Each of these colours can have a value of hex 00 (decimal 0), which is the lightest to hex FF (decimal 255) which is the most intense. So 000000 is white; FF0000 is pure red; 00FF00 is pure green; 0000FF is pure blue and FFFFFF is black. Greys are given by having all three values set to the same, so 333333, 666666, 999999 and so on are all shades of grey. These numbers are put into the array. Because the characters are short I've used an alternative method of filling the array and that is var hexNum = new Array("0","1","2","3","4","5","6","7","8", "9","A","B","C","D","E","F");

The web-safe colours are those that should appear the same on all computers and these just use a combination of numbers - 00, 33, 66, 99, CC and FF.

The random number is generated, the same as the other methods on this page. The only difference is that several are generated in this code. This is done by using the code for (cnt=1;cnt<7;cnt++) or for (cnt=1;cnt<4;cnt++) which is known as a FOR loop. The generated array indexes are joined to each other, this is done by the code rdmHexClr = rdmHexClr + hexNum[rdmNum];

In programming, computers remember the values of the variables as they are being manipulated. So the original value of rdmHexClr  on the right of the equals sign gets the value of hexNum[rdmNum] added to it and then remembered as the new value of rdmHexClr. This also explains why the line rdmHexClr = "#" + rdmHexClr; works.

Random Links

Now and then people ask how to write a button, that when clicked takes their visitors to a random page on their site.

To do this place the following code in the HEAD section...

<script language="javascript">
<!-- Hide the script from old browsers
function doLink(){
//Define and populate the array
var links = new Array;
links[0]="lycos1.htm";
links[1]="srcheng1.htm";
links[2]="wbasics.htm";
links[3]="wbrowser1.htm";
links[4]="wdesign1.htm";

//Generate a random number then display the image from that array index
rdmNum = Math.floor(Math.random()*links.length);
window.open(links[rdmNum]);
}
-->
</script>

If you want the new page to open in the current window, change the line window.open(links[rdmNum]); to document.location=links[rdmNum]

Where the button is to appear, in the BODY section put...

<form>
<p align="center"><input type="button" value="Click Here for Random Page" name="btnRdmLnk" onclick=doLink()></p>
</form>

In April 2005, I got an email from someone who found a very good use for the randomization codes on this page, they made electronic flashcards for helping their son to read.

Random Numbers

Random Quotes

Random Multi-line Quotes

Random Images

Random Background Image

Random Background Colour

Random Links

Web Stuff | Audio | Basics | Browser | Code Tips | Design | Fonts | Forms | Frames (Page 1), (Page 2) | Images (Page 1), (Page 2) | Links | Random | Redirection | Sound | Video | Search Engines | Lycos UK | Home Server (Page 1), (Page 2), (Page 3)

HomePage | Optical Illusions | War Stories | QBasic | Dads Navy Days | Bristol | Bristol, USA | Bristol, Canada | Terre Haute | Miscellany | Web Stuff | About Ray | Site Map | Site Search | Messages | Credits | Links | Web Rings

This page created 21st October 2004, last modified 24th April 2005


GoStats stats counter