Random Numbers & Random Events
You are here: irt.org | Articles | JavaScript | Text, String, and Number | Random Numbers & Random Events
Published on: Sunday 3rd August 1997 By: Martin Webb
Introduction
This article will descibe how to use random numbers to create random
events. I'll describe how to show images and text at random, how to
show one of several forms randomly, refer to random banner adverts,
random urls, random background color and images, how to generate a
random questionnaire, and random frames.
Since the introduction of JavaScript, there has always been an inbuilt
random method, however, on Netscape this method was, up until Netscape
3.0, only available on Unix platforms.
The inbuilt random method produces a floating point number between 0
and 1:
var number = Math.random();
|
If you just need one number to change the document at the moment it is
viewed time, then you can always grab the current time and use the
current value of the seconds:
var now=new Date();
var number = now.getSeconds();
|
This would produce a number between 0 and 59 based on the current
time. This can be used to provide a smaller range of numbers by
taking the modulus of the current time:
var now=new Date();
var number = now.getSeconds()%43;
|
This produces a number between 0 and 42.
The Central Randomizer
The Central Randomizer has an excellent random number generator for public domain use (as long as it remains unchanged):
<script language="JavaScript"><!--
// The Central Randomizer 1.3 (C) 1997 by Paul Houle (houle@msc.cornell.edu)
// See: http://www.msc.cornell.edu/~houle/javascript/randomizer.html
rnd.today=new Date();
rnd.seed=rnd.today.getTime();
function rnd() {
rnd.seed = (rnd.seed*9301+49297) % 233280;
return rnd.seed/(233280.0);
};
function rand(number) {
return Math.ceil(rnd()*number);
};
// end central randomizer. -->
</script>
|
To use the Central Randomizer code, ensure it is placed between the
<HEAD> and </HEAD> HTML tags.
To create a random floating point number use: rnd(), to
create a random integer, say between 1 and 10, use rand(10).
For the remainder of this article I'll be using the Central Randomizer
to create random numbers, this will ensure compatibility with Netscape
2.x and Microsoft Internet Explorer 3.x. Therefore, for all of
the following examples to work you MUST include the previous snippet
of code.
Random Images & Text
This is one of the most simplest things that can be done with random
numbers.
For this example we'll assume that we have ten images named
banner1.gif through to banner10.gif, one of which we
want displayed randomly each time the document is loaded:
<script language="JavaScript"><!--
document.write('<img src="../images/banner' + rand(10) + '.gif" width=400 height=40>');
//--></script>
|
Which when run produces the following:
If the images are not named in an numeric order, or the images are of
different type or sizes, then you can check the value of the random
number and then display the required image:
<script language="JavaScript"><!--
var number = rand(10);
if (number == 1) {
var picture = "one.gif";var width = 400;var height = 40;
}
else if (number == 2) {
var picture = "two.jpg";var width = 200;var height = 20;
}
...
...
else if (number == 9) {
var picture = "nine.gif";var width = 450;var height = 450;
}
else if (number == 10) {
var picture = "ten.jpg";var width = 40;var height = 400;
}
document.write('<img src="../images/' + picture + '" width=' + width + ' height=' + height + '>');
//--></script>
|
Random text is just as easy:
<script language="JavaScript"><!--
function male() {
var number = rand(5);
if (number == 1) return('Robert');
if (number == 2) return('John');
if (number == 3) return('Paul');
if (number == 4) return('Peter');
if (number == 5) return('Simon');
}
function female() {
var number = rand(5);
if (number == 1) return('Jane');
if (number == 2) return('Mary');
if (number == 3) return('Anne');
if (number == 4) return('Helen');
if (number == 5) return('Jenny');
}
//--></script>
XYZ dating agency matches: <script>document.write(male())</script>
with <script>document.write(female())</script>.
|
Which when run produces:
XYZ dating agency matches:
with .
Random Forms
There is nothing more mundane than always being presented with the
same form to fill in ech time you visit a page. Especially if you dont
intend on filling out the form. This idea, adds a novel twist to
forms, by showing a random form each time the page is loaded. This
way the page looks different, and might encourage your visitors to
send in some feedback.
The following example demonstrates the principle:
<script language="JavaScript"><!--
function sendForm(object) {
if (navigator.appName.indexOf('Netscape') > -1) {
object.encoding = 'text/plain';
object.action = 'mailto:someone@somewhere.com';
}
return true;
}
var number = rand(2);
document.write('<form name="emailForm" method="post" action="/cgi-bin/userform.cgi" onSubmit="return sendForm(document.emailForm)">');
document.write('<table width=595 border=0 bgcolor="#aaaaff" cellspacing=0 cellpadding=10><tr><td valign=top>');
document.write('<input type="hidden" name = "JavaScript \'No Content\' Web Site" value = "Notify">');
document.write('<input type="hidden" name = "SendMailTo" value = "someone@somewhere.com">');
document.write('<input type="hidden" name = "redirect" value = "utility/thanks1.htm">');
if (number == 1) {
document.write('Send any comments, questions or requests regarding the<br>');
document.write('JavaScript <font color=maroon><b><em>\'No Content\'<\/em><\/b><\/font> Web site to <a href="mailto:someone@somewhere.com">someone@somewhere.com<\/a>');
document.write('<p>Enter your message here<br><textarea name="comments" rows="6" cols="40"><\/textarea>');
}
else {
document.write('<p>To ensure you receive notification when the JavaScript <font color=maroon><b><em>\'No Content\'<\/em><\/b><\/font> Web site is updated, register your e-mail address.');
document.write('<p>Register: <input type="radio" name="Register" checked value="register">');
document.write('<p>Unregister: <input type="radio" name="Register" value="unregister">');
}
document.write('<p>Enter your your e-mail address here<br><input name="required-email" size="40">');
document.write('<p>Enter your name here<br><input type="text" size="40" name="name">');
document.write('<p><input type="submit" value="Submit"><\/td><\/tr><\/table><\/form>');
//--></script>
|
Random Adverts
Random banner adverts have already been covered in a previous article:
Random Banner Adverts. However this
used the time to create the 'random' number which quite often produced
the same value - as it was time based. The following rewritten
example produces a truely random advert:
<script language = 'JavaScript'><!--
function Href(dest,image,text) { this.dest = dest; this.image = image; this.text = text; }
function setHref(dest,image,text) { myHref[item++] = new Href(dest,image,text); }
function replace() {
var now = new Date();
var random = rand(item) - 1;
document ['banner'].src = myHref[random].image;
document.links[0].href = myHref[random].dest;
window.setTimeout('replace()',5000);
}
function go_to() {
location.href = myHref[random].dest;
}
var item = 0;
var myHref = new Array();
setHref('../../articles.htm','../images/banner1.gif','Click to go to Articles page');
setHref('../../index.htm','../images/banner2.gif','Click to go to Home page');
if (navigator.appName == "Netscape") {
var now = new Date();
var random = rand(item) - 1;
document.write('<a href="javascript:go_to()">');
document.write('<img name="banner" width=400 height=40 border=1 ');
document.write('alt="Image" src="' + myHref[random].image + '"><\/A>');
}
if (navigator.appName == "Netscape" && parseInt(navigator.appVersion) >= 3) {
window.setTimeout('replace()',5000);
}
//--></script>
|
Random URL's
As you can see with the previous example it is possible to change the
target location. The next few examples show how to go to a random
location.
The following JavaScript is used in the next three examples. It
creates a simple array of URL's and defines a
randomJump() function:
<script language="JavaScript"><!--
var item = 0;
var URL = new Array();
URL[item++] = '../../articles.htm';
URL[item++] = '../../index.htm';
function randomJump() {
var random = rand(item) - 1;
location.href = URL[random];
}
//--></script>
|
Each of the following three examples uses the randomJump() function to
determine the random location.
<a href="javascript:randomJump()" onMouseOver="self.status='';return true">Random Link</a>
|
<FORM><input type=button value="Random Link" onClick="randomJump();return false"></form>
|
<a href="javascript:randomJump()" onMouseOver="self.status='';return true"><img src="random.gif" width=17 height=24 border=0></a>
|
The three examples look something like this:
Random Backgrounds
Once the background image has been set, it is not possible to change
it. However whilst the document is loading it is possible to set a
random background image:
<script language="JavaScript"><!--
document.write('<body background="image' + rand(10) + '.gif">');
//--></script>
|
Random Questionnaire
If you're still having problems getting feedback from your customers
you can always slap a questionnaire in front of them. This following
example will randomly open another browser window with a questionnaire
form. The frequency of this is kept low enough so as to not to become
annoying for frequent visitors:
<script language="JavaScript"><!--
var number = rand(20);
if (number == 1) {
questionnaire = window.open('question.htm','myWindow','scrollbars=yes,status=no,width=640,height=480')
}
//--></script>
|
Random Frames
Whilst writing this article I was asked, was it possible to use random
links to alter the contents of another frame.
The following example defines several possible urls, it then chooses
three at random, and then creates the frameset.
The right frame, will initially contain the first random url. The
left frame, then lists the three random links, which when chosen load
into the right frame.
<html>
<head>
<title>Random Frames</title>
<script language="JavaScript"><!--
// The Central Randomizer 1.3 (C) 1997 by Paul Houle (houle@msc.cornell.edu)
// See: http://www.msc.cornell.edu/~houle/javascript/randomizer.html
rnd.today=new Date();
rnd.seed=rnd.today.getTime();
function rnd() {
rnd.seed = (rnd.seed*9301+49297) % 233280;
return rnd.seed/(233280.0);
};
function rand(number) {
return Math.ceil(rnd()*number);
};
// end central randomizer. --></script>
</head>
<script language="JavaScript"><!--
var item = 0;
var URL = new Array();
URL[item++] = 'http://www.yahoo.com';
URL[item++] = 'http://www.netscape.com';
URL[item++] = 'http://www.microsoft.com';
URL[item++] = 'http://developer.netscape.com';
URL[item++] = 'http://home.netscape.com/home/whats-cool.html';
URL[item++] = 'http://home.netscape.com/home/whats-new.html';
var random1 = URL[rand(item)];
var random2 = URL[rand(item)];
var random3 = URL[rand(item)];
document.write('<frameset cols="25%,*">');
document.write('<frame src="left.htm" name="left">');
document.write('<frame src="' + random1 + '" name="right">');
document.write('<\/frameset>');
//--></script>
</html>
|
The following code, contained in left.htm, then uses the
random1, random2 and Mrandom3 links from
the parent frame. It uses the onMouseOver event
handler to hide the target locations:
<HTML>
<body>
<script language="JavaScript"><!--
document.write('<a href="' + parent.random1 + '" target="right" onMouseOver="self.status=\\'\\';return true">Random Link 1<\/a><p>');
document.write('<a href="' + parent.random2 + '" target="right" onMouseOver="self.status=\'\\';return true">Random Link 2<\/a><p>');
document.write('<a href="' + parent.random3 + '" target="right" onMouseOver="self.status=\\'\\';return true">Random Link 3<\/a><p>');
//--></script>
</body>
</html>
|
Why not try out this example?
Feedback on 'Random Numbers & Random Events'
View the profile on Martin Webb and the list of other Articles by Martin Webb.
|