Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Understanding the Random Function in JavaScript

In this article we will discuss about randomizing function in javascript.

Random content generation is one of the major functions implemented through javascript. This is not only random number generation but also used to generate any content, calculation, image selection etc.

Introduction:

The random function in javascript is used to generate some random content at runtime. The most common example of this feature is to generate random numbers on the fly. The random () method of the Math object enables us to get random numbers at runtime. The random function in the Math object returns a random number between zero and one.

How it works:

Generating a random content on a web page can be divided into three sections:

  • Define the entity
  • Define the randomize function
  • Use the randomize function to get the desired entity

Define the entity:

In this section, we generate a random quote, which is required to define a long list of quotes. These quotes will be used by the script to pick one at a time. This is achieved by using an array which is a one dimensional matrix used to store every possible piece of information. From this array the randomizing function will pick the random (in this case) quote. Let us consider the following code snippet:

Listing 1: creating the random quote array

quotes = new Array
(
	" This is quote 1 ",
	" This is quote 2 ",
	" This is quote 3 ",
	...
	" This is the last quote "
) ;

As we can see this is a simple way in which we define an array in javascript. We create this array with some fixed quotes.

Define the randomize function:

Once the array from where the random entity is picked, is defined, we need a function which delivers a random result to pick the said entity. There are many ways to do this. The following code snippet uses the timestamp to pick a random entity from the array:

Listing 2: creating the random function

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 );

};

Here, the first two lines are used to define two elements, based on the date and time. These elements are used in the next line, which is the function rnd (). This function is defined basically as a little sum which uses the time and date as used before which in turn is then used in the function rand (number) to define a function that will return a random number based on the time and date.

Displaying the random entity:

Once the random function is defined, it is quite simple to return a random entity. A simple call to the script to write the quote associated with the number generated by the random function:

Listing 3: call to the random function

document.write( quotes[ rand( quotes.length )-1 ] )

Here, rand is the function as defined above, (quotes. Length)-1 is the range of quotes we have defined in the array and document.write is the JavaScript command that returns the "value" which is generated within the parenthesis. It is then this entity, which will be displayed on the webpage. Now let’s have a look into the entire script:

Listing 4: The full source code of the function

quotes = new Array
( 
" This is quote 1 ",
" This is quote 2 ",
" This is quote 3 ",
...
" This is the last quote "
) ;
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);

};
document.write( quotes[ rand( quotes.length )-1 ] )

Finally we as a developer have to decide where to include this code in our html page. Here we have two options:

  • within the html page which we will be using or
  • write a separate script and call the function when the page is loaded

If we use the first option we need to include the script tag within the html header or body as under:

Listing 5: include the source code within the html page

<script type = "text/javascript">
// The script code goes here
</script>

This option should be used in situation where the script is used only for a given circumstance. This is not the generic approach. Moreover we cannot re-use the script if required. The second option is more generic approach and supports the reusability feature. Here the function is written in a .js file which is called when the page is loaded. This is done as under:

Listing 6: include the js file

<script type="text/javascript" src="myscript.js">
</script>

Using the Math random function:

The random () method of the Math object enables us to get random numbers at runtime. The random function in the Math object returns a random number between zero and one. We can make a random quote generator or have another type of random script. The most important part here is to know the range within which we want to get the random integer. By default, the random function returns a random number between zero and One. This is not very useful if we want to have a random number between zero and another number e.g. 5. In this case we achieve our target if we multiply the output of Math.random() function by 5. This is done as under:

Listing 7: get the random number between 0 and 5.

var ran_number =  Math.random() * 5; 

The above code will get the random number between 0 (included) and 5 (excluded) but the generated numbers will not be integers. If we need to have the integer values we need to change the above code as under:

Listing 8: get integer the random number between 0 and 5

var ran_number_unrounded =  Math.random() * 5; 
var ran_number = Math.floor( ran_number_unrounded )

Now consider the following code snippet:

Listing 9: a complete html code along with javascript function using randomization

<HEAD>
 <SCRIPT language="JavaScript">
<!--
function get_random()
{
    var ranNum = Math.floor(Math.random()*5);
    return ranNum;
}

function getaQuote()
{
   var whichQuote = get_random();

    var quote = new Array(5)
     quote[0] = " I love JavaScript..sometimes. ";
     quote[1] = " Why are you pushing my button? ";
     quote[2] = " The button you pushed can\'t push you back. You bully, you! ";   
     quote[3] = " This alert is here to inform you that alerts are annoying. ";
     quote[4] = " Which came first, the button or the alert? ";
  
   alert(quote[whichQuote]);
  }
//-->
</SCRIPT>
</HEAD>

<BODY>
<FORM name = " form1 ">
<INPUT TYPE = " button " value = " Get a Quote! " onClick = " getaQuote() ">
</FORM>   
</BODY>

Here the function get_random () returns a random number between 0 and 4 (both included). The next function, getaQuote () uses the random number generated by this function as an array index and returns the message from the array.

Conclusion

To conclude this discussion we can keep the following points in mind while using random function. It is implemented in wide are of functionalities in modern web applications and portals.

  • Random Function is used to generate random content at runtime
  • The process of generating random content can be divided into three sections :
    • define the entity
    • define the function
    • get the desired entity using the random function
  • The most common used example is getting a random number at runtime.

See also:



Website: www.techalpine.com Have 16 years of experience as a technical architect and software consultant in enterprise application and product development. Have interest in new technology and innovation area along with technical...

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login