Helping ordinary people create extraordinary websites!
HOME TUTORIALS SCRIPTS WEB HOSTING BLOG FORUM
Get Our Newsletter
Your Email:

How to Setup a Randomising Function

By Arbitrary Constant
2007-11-17


Displaying the random entity

Once we have a randomising function, returning a random entity is straightforward: we simply call upon the script to write the quote associated with the number generated by the random function:
document.write(quotes[rand(quotes.length)-1])
Here, rand is the function as defined before, (quotes.length)-1 is the range of quotes we defined in the array and document.write is the JavaScript command that returns the "value" created within the parenthesis. It is then this entity that will be displayed on the webpage.
Thus, the entire script looks a little like this:
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])
All that remains now is to decide where to include the code for you html page. There are two main options: 1) within the html page on which you want to utilise it or 2) as an external script called upon by the html page when it loaded. In the first case, you need to include the script tag within the html header or body:
<script type="text/javascript">
insert script here
</script>
The first method should ideally be used for a script that is used only in a particular circustance, whereas the external link is best employed when a script is used on many changes and would therefore require much more time if it were to be altered on each page it is used. That is the method used on this website.
The second method is similar to that employed for a style sheet and involves an external link to the script in the following manner:
<script type="text/javascript" src="script.js">
</script>


Tutorial Pages:
» How to set up a randomising function
» Defining your entities
» Defining a randomising function
» Displaying the random entity


 | Bookmark
Related Tutorials:
» JavaScript Debugging Techniques with Firebug
» Striped Tables Using JavaScript
» Opening PDFs in a New Window with JavaScript
» Essential Javascript -- A Javascript Tutorial
» Submit Forms Conditionally using JavaScript
» Introduction to JavaScript Tutorial