Web Hosting
We've partnered with HostGator for reliable, affordable hosting starting at $3.95/mon. Use coupon code "javascriptkit25" for 25% off any package.

. Creating a random link out of a specified group of links

One of the most common uses of a random engine is to create a random link out of a predetermined group of links. We specify in advance the urls to be put in a "black box", and have the random engine randomly draw one out to follow. Let's first create a random link out of three predetermined links:

<script type="text/javascript'>
function random_3(){
var myrandom=Math.round(Math.random()*2)
var link1=""
var link2=""
var link3=""
if (myrandom==0)
else if (myrandom==1)
else if (myrandom==2)
<input type="button" value="random link!" onClick="random_3()">

The meat of this example is the following:

var myrandom=Math.round(Math.random()*2)

The above creates a random integer between 0 and 2. The number could be 0,1, or 2. Let's see more finely why this is the case.

1) Math.random() always produces a random number between 0 and 1
2) Math.random()*2 always produces a random number between 0 and 2
3) Math.round(Math.random()*2) always produces a random integer between 0 and 2

Understanding the above enables us to create a random integer that falls between 0 and any integer! Lets extend the current example to create a random link out of 10 predetermined links:

<script type="text/javascript">
function randomlinks(){
var myrandom=Math.round(Math.random()*9)
var links=new Array()

<input type="button" value="random link!" onClick="randomlinks()">

As you can see, to create a random link out of 10, we multiplied Math.random() by 9 to first generate a random number that falls between 0 and 9. Then by using the round() method, we molded this number into an integer. Finally, a new technique here- I use arrays to store the links so I can easily reference here. This is a lot more desirable when you have a lot of links to define and need to pick one out.

Copyright 1997-2014 JavaScript Kit. NO PART may be reproduced without author's permission.