[ Team LiB ] Previous Section Next Section

15.1 Displaying a Random Aphorism

NN 4, IE 4

15.1.1 Problem

You want a random choice from a library of famous quotes to appear in a location on your home page.

15.1.2 Solution

The backward-compatible (to Version 4 browsers) solution is to use the document.write( ) method to insert your quotation element while the page loads. But first, start by creating an array of sayings in the head section. Each array entry is a custom object containing the saying and author's name:

var quotes = new Array( );
quotes[quotes.length] = {quote:"One should eat to live, and not live to eat.", 
                          author:"Moliere"};
quotes[quotes.length] = {quote:"For man is man and master of his fate.", 
                          author:"Tennyson"};
quotes[quotes.length] = {quote:"History is more or less bunk.", 
                          author:"Henry Ford"};
quotes[quotes.length] = {quote:"You should never have your best trousers on when you 
                          turn out to fight for freedom and truth.", 
                          author:"Ibsen"};
quotes[quotes.length] = {quote:"It is vain and foolish to talk of knowing Greek.", 
                          author:"Woolf"};
...

The following getSaying( ) function uses a random number calculation to obtain an index for the array to select a saying. The function then assembles the HTML that is to appear in the page:

function getSaying( ) {
    var currIndex = Math.floor(Math.random( ) * (quotes.length));
    var output = "<p class='quote'>" + quotes[currIndex].quote;
    output += "<span class='author'>&nbsp;&nbsp;&nbsp;-- ";
    output += quotes[currIndex].author + "</span></p>";
    return output;
}

Then, in the place where you wish the saying to appear, include a script that invokes the getSaying( ) function:

<script type="text/javascript">document.write(getSaying( ))</script>

15.1.3 Discussion

The operative part of the Solution is the interaction between the array of objects and the way the objects are retrieved when needed. The array creation code uses the length of the array to determine the index values of the entries. This simplifies any editing of the list, as you don't have to rearrange index numbers as you add or remove objects from the array.

Computation of the (pseudo) random number is simplified here because we're looking for a number between zero and the number of items in the array (inclusive). Once the array index is available, it is used to access two properties of the array entry's object.

HTML formatting is strictly up to your page design. In the Solution, class names are assigned to the two segments of the saying. A simple style sheet that supplies distinct font characteristics for the saying and author's name might be like the following:

<style type="text/css">
  .quote {font:bold 12px serif}
  .author {font:italic 12px serif}
</style>

Your design is likely to be more detailed.

The Solution displays a potentially different saying each time the user loads the page. If you'd like to preserve the same saying for all visits to the page on a given day, you need to add some cookie support to store the date and index number associated with that date. You can build this support into the getSaying( ) function so that it first checks for a named cookie holding date information. If the date is different from the current date, the current date is preserved in the cookie and a new random index number is calculated. But if the cookie date matches the current date, the cookie's index number is assigned to the currIndex variable inside the function.

Numerous variations on the daily saying application abound on the Internet. Some like to peg a particular phrase or content to one of the seven days of the week or a date in the month. For example, each day of the week has a zero-based index number associated with it in the JavaScript Date object (values 0 through 6, with Sunday being 0). It's easy to create a new date object and get the day number to use as an index for the array of sayings:

var today = new Date( );
var currIndex = today.getDay( );

Just be sure to have as many items in the array as the possible numbers that are assignable to the currIndex variable.

Another application is to display random pictures, such as one from a list of image URLs from a product catalog�a featured product. In this case, the array of custom objects contain image and URL information:

var imgLinks = new Array( );
imgLinks[imgLinks.length] = {src:"images/prods/x25.jpg", url="products/x25.html"};
...
function getRandomImage( ) {
    var currIndex = Math.floor(Math.random( ) * (quotes.length));
    var output = "<a href='" + imgLinks[currIndex].url + "'>";
    output += "<img src='" + imgLinks[currIndex].src; 
    output += "' alt='Product of the day!' />" + "</a>"
    return output;
}

At each visit, the user should see a different featured product, with a link directly to the product page.

15.1.4 See Also

Recipe 3.1 for creating an array; Recipe 3.8 for creating a custom object.

    [ Team LiB ] Previous Section Next Section