Current course:

Javascript Random numbers

Random Numbers are used in programming for multiple reasons. Choosing random images (banners, ads), messages or numbers for games, such as, lotteries. There are an infinite number of ways to use random numbers in art.

To create a random integer with Javascript, we must use two Javascript methods - Math.random() and Math.floor().

Math.random() generates a random number between zero and just less than 1 (ie. 0.99999...). Each time the code is run, it will create a new random number.

Math.floor() rounds DOWN to the nearest integer or round number. For example Math.floor(1.85) would equal 1.

Example 1

This will alert a random number when the link is clicked:

<script type="text/javascript">
      function alertRandomNumber() {
            alert(Math.floor(Math.random() * 100 + 1));

<a href="javascript: alertRandomNumber();">Generate a random number between 1 and 100.</a>

Generate a random number between 1 and 100.

Example 2

This example uses Math.random to retrieve a random URL from an array
<script type="text/javascript" >
      var myURLs = new Array("", "", "", "");

      function alertRandomLink() {
            var myRandom = Math.floor(Math.random() * myURLs.length);
            var randURL = myURLs[myRandom];
Alert random link

Example 3

Instead of just alerting the url, lets try directing the user to a random URL:

<script type="text/javascript" >
      function randomPage() {
            var myURLs = new Array("", "", "", "");

            var myRandom = Math.floor(Math.random() * myURLs.length);
            window.location = myURLs[myRandom];
//if you wanted to open a new window rather than having the URL load into the current one, you would use

Go to a random page

Example 4

Random Images - Displays a different image everytime the window is refreshed.
NOTE: Make sure images exist in a folder in your website first!
<script type="text/javascript" >
      var myPix = new Array( "images/caricature.jpg" , "images/smiley.jpg" , "images/arrow.jpg");

      function choosePic() {
            var randomNum = Math.floor( Math.random() * myPix.length);
            document.getElementById('myPicture').src = myPix[randomNum];


<body onload="choosePic();"> //call function using the ONLOAD in the body tag
      <img src="testImages/caricature.jpg" id="myPicture">

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