JavaScript Randomness
syllabus | schedule | assignments | Web Resources | ARTC courses
[Intro]     [Tags]     [CSSStyles]     [Lists]     [Links]     [ImageTypes]     [Optimization]    [GlobalCSS]     [CSSBackgrounds]
[Tables]     [Slices]     [IR Rollovers]     [Animated GIFs]     [JS Rollovers]     [CSS Margins]     [Windows]     [Video]     [Metatags]     [Imagemaps]     [FormInput]     [FormAtttributes]    [AdvancedForms]    [WhatisJavaScript]    [Windows2]    [Windows3]    [BrowserInfo]    [StatusBar]    [Alerts]    [Randomness]    [Frames]    [iFrames]    [Frames2]   
Random Numbers are used in programming for multiple reasons, i.e., choosing random images (banners, ads), messages or numbers for games, such as, lotteries.

Two MATH methods are used within the RANDOM calculation: Math.random(), which chooses the number and Math.floor(), which truncates decimal values to return an integer.

In HEAD:

<script>

var n =10; //10 is the maximum random number possible
for (i=0; i < 10; i++) { //runs the random generator 10 times

document.write(Math.floor(Math.random() * n ) + "<br>");

}

</script>

Try combining the random number code with the prompt user code. This sample will ask the user for a number that will be the maximum random number. <sample>

In HEAD:

<script>

var answer = prompt( "Please enter a number: " ); //answer equals a string type, ex: "4"
var num = eval( answer ); //eval() converts answer from a string to an integer type

for (i=0; i < 10; i++) {

document.write(Math.floor(Math.random() * num ) + "<br>");

}

</script>

TRY adding a second prompt, with variable, to ask the user how many random numbers they need.

 

Random Link - The following is sample code that allows you to randomly select from a prescribed list of URLs. This allows you to change which website or html doc a link is pointing to. This way when your viewer returns to the page they are not always directed to the same information, thus taking advantage of the non-linearity of the web. <sample>

In HEAD:

<script>

//specifies total # of random links
var myNum = 4;

//container for my URLs
var myURLs = new Array(myNum);

//initialize each index of the array to equal a different URL. Array index starts at 0
myURLs[0] = "http://www.bgsu.edu";
myURLs[1] = "http://www.syr.edu";
myURLs[2] = "http://www.cia.edu";
myURLs[3] = "http://www.cmu.edu";

//initialize var to equal a random number
var myRandom = Math.floor(Math.random() * myNum);

//randURL equals the randomly chosen URL and places it in an <a href> tag
var randURL = "<a href=' " + myURLs[myRandom] + " '>";

//concatenates the link name and closing tag
//result: <a href="http://bgsu.edu>Where are you going?</a>

randURL += "Where are you going?" + "</a>";

//writes to the HTML doc.
document.write(randURL);

</script>


To randomly direct the user to a URL without the user clicking on a link <sample>

In HEAD:

<script>

var myNum = 4;

var myURLs = new Array(myNum);

myURLs[0] = "http://bgsu.edu";
myURLs[1] = "http://syr.edu";
myURLs[2] = "http://cia.edu";
myURLs[3] = "http://cmu.edu";

var myRandom = Math.floor(Math.random() * myNum);

//writes message in html for user to read
document.write("You are being redirected randomly..");

//directs the browser to the new URL
location.replace( myURLs[ myRandom ] );

</script>

 

Random Images - Displays a different image everytime the window is refreshed. <sample>
NOTE: Make sure images exist in a folder in your website first!

In HEAD:

<script>

//list all your images, including the folder they are in
myPix = new Array( "testImages/lion.jpg" , "testImages/tiger.jpg" , "testImages/bear.jpg" , "testImages/images1.jpg" , "testImages/images2.jpg" , "testImages/images3.jpg" );

//number of images
imgCount = myPix.length;

function choosePic() {

if ( document.images ) {

//picks a random number based on number of images
randomNum = Math.floor( Math.random() * imgCount );

//loads random pic as source
document.myPicture.src = myPix[ randomNum ];

}

}

</script>

In BODY:

<body onload="choosePic();"> //call function using the ONLOAD in the body tag

//Use an IMG tag as a place holder for the random image to load - must have SRC and NAME attributes
<img src="testImages/anything.gif" name="myPicture">

</body>

NOTE: Do NOT put width and height in the image tag unless the images are all the same size and proportion.

<ref: javascriptworld.com>