Creating a Random Link Generator


A random link generator is basically a link that takes you to a different location every time you click it. In the past, the only way to implement such a link was to use a CGI script. With JavaScript, you can move the process of choosing a link from a script on the server to a script running in the browser.

In the following sections, you'll learn how to create three different random link generators. The first uses an inline <script> tag and a single function, the second uses event handlers, and the third uses arrays within a script.

Note

An inline <script> tag is one that is embedded in the <body> section of an HTML document rather than in the <head> section, as is more common.


Task: Exercise 13.1. The Inline Random Link Generator

Because the JavaScript code for this generator will be incorporated into a standard HTML document, open the text editor or HTML editor that you normally use for designing web pages and create a new file called random.html.

In this new file, create a basic document framework like the following one. You should recognize all the elements of this document from preceding lessons, including the <a>...</a> tag combination on the third-from-last line:

Input

<html> <head> <title>Random Link Generator</title> </head> <body> <h1>My random link generator</h1> <p>Visit a <a href="dummy.html">randomly selected</a> site from my list of favorites.</p> </body> </html>


If you ran this document as it is, you would see a result like the one shown in Figure 13.1.

Output

Figure 13.1. The Random Link Generator page.


Now you can add some JavaScript code to turn the link into a random link generator. First, add a <script> tag to the <head> section immediately after the <title> tag block:

<title>Random Link Generator</title> <script language="JavaScript"> <!-- the contents of the script need to be hidden from other browsers the JavaScript code goes here. // End of script --> </script> </head>


The next step involves adding the code that generates the random links based on a list of your favorite sites. Inside the <script> tagand comment tagyou'll create a function called picklink(). First, you need to define the function:

function picklink() {  your JavaScript code goes here. }


The code that follows actually makes the picklink() function work, with a list of four sites to choose from.

function picklink() {  var linknumber = 4;  var linktext = "nolink.html";  var linkselect = Math.floor(linknumber * Math.random()) + 1;  if (linkselect == 1)  {   linktext = "http://www.netscape.com/"  }  if (linkselect == 2)  {   linktext = "http://www.lne.com/Web/"  }  if (linkselect == 3 )  {   linktext = "http://java.sun.com/"  }  if (linkselect == 4)  {   linktext="http://www.realaudio.com/"  }   document.write('<a href="' + linktext + '">randomly selected</a>'); }


To help you understand what this code is doing, I'll explain it section by section. The first two lines following the function definition declare some work variables used inside the function: linknumber tells the function how many links it has to choose from, and linktext is a work variable that holds the value of the URL for the selected random link.

The next line creates a number called linkselect, which contains an integer between 1 and the value set in linknumber. It does so by multiplying the number of links available with a random number between 0 and 1, obtained using Math.random() (random() is a method built into the Math object). This returns a number such as 2.138413 or 0.13451. The Math.floor() method then returns the highest integer less than that number. That leaves us with a number between 0 and 3. Adding 1 to that result gives us a number between 1 and 4, which is what we need.

The set of if statements that follows checks the randomly selected value assigned to linkselect. When a match is found, it assigns a URL to the variable linktext. You can add as many URLs as you want here, but remember that you need to alter the value of linknumber so that it reflects how many links you've defined.

After you assign a URL to linktext, the next step is to create the physical link by using a document.write() method:

document.write('<a href="' + linktext + '">randomly selected</a>');


The value inside the parentheses takes advantage of JavaScript's capability to add strings of text together. In this case, '<a href="', the values of linktext, and '">randomly selected</a>' are added together to create a properly formed link tag.

Now that you've defined picklink() in the <script> definition, all that remains is to replace the original anchor tag from the original page with the new link created by picklink(). You can do so in various ways, but the simplest method is to embed a call to picklink() inside the body of your document, as shown here:

<p>Visit a <script language="JavaScript">picklink()</script> site from my list of favorites.</p>


Note

Some JavaScript purists might argue that you should include <script> blocks only in the <head> section of an HTML document, and for the most part they're correct. But you'll break this rule in this exercise to see how inline script calls work. In the following exercise, you'll learn about a mechanism that enables you to create a random link generator without the use of inline <script> tags.


The Completed Document

Here's the final random number HTML page with all the JavaScript intact.

Input

<html> <head> <title>Random Link Generator</title> <script language="JavaScript"> function picklink() {  var linknumber = 4;  var linktext = "nolink.html";  var linkselect = Math.round((linknumber - 1) * Math.random()) + 1;  if (linkselect == 1)  {   linktext = "http://www.netscape.com/"  }  if (linkselect == 2)  {   linktext = "http://www.lne.com/Web/"  }  if (linkselect == 3 )  {   linktext = "http://java.sun.com/"  }  if (linkselect == 4)  {   linktext="http://www.realaudio.com/"  }  document.write('<a href="' + linktext + '">randomly selected</a>'); } </script> </head> <body> <h1>My random link generator</h1> <p>Visit a <script language="JavaScript">picklink()</script> site from my list of favorites.</p> </body> </html>


Task: Exercise 13.2. A Random Link Generator Using an Event Handler

Besides being bad style-wise, using inline <script> tags can cause unpredictable problems when images are displayed on a page. If you want to avoid such difficulties, it's safest to use scripts only in the <head> block, when practical.

However, this poses a problem for your random link generator, which needs to alter the value of a link each time it's used. If you can't include <script> tags in the <body> of a document, how can the link be randomly selected?

Whenever you click a link, a button, or any form element, the browser generates an event signal that can be trapped by one of the event handlers mentioned in Lesson 12, "Introducing JavaScript." If you take advantage of this fact, as well as the fact that each link in a document is actually stored as an object that can be referenced by JavaScript, you'll find it surprisingly easy to alter your existing script to avoid the need for an inline <script> tag.

First, look at the changes that you need to make in the body of the document to accommodate an event handler. In this exercise, the inline <script> tag is replaced by a normal <a> tag, as shown here:

<p>Visit a <a href="dummy.html">randomly selected</a> site from my list of favorites.</p>


Next, associate an onclick event handler with the link by including the handler as an attribute of the <a> tag. When onclick is used as an attribute, the value assigned to it must represent a valid JavaScript instruction or function call. For this exercise, you want to call the picklink() function created previously and make the URL that it selects overwrite the default URL, defined in the <a> tag as HRef="dummy.html".

This job is easy because each link is actually stored as an object of type link, which contains the same properties as the location object mentioned in Lesson 12. As a result, all you need to do is assign a new value to the HRef property of the link in the onclick event handler, as shown here:

<p>Visit a <a href="dummy.html"   onclick="this.href=picklink()">randomly selected</a> site from my list of favorites.</p>


Note

Earlier I explained that this is a reference to the current object. In this example, this points to the link object associated with the anchor tag in which it is used, and this.href indicates the href property of the object. Therefore, by assigning a new value to this.href, you change the destination URL of the link.


With the onclick handler set up, you need to alter the picklink() function. Because you're no longer physically writing anything onto the web page, you can remove the document.write() function. But in its place, you need some way for the value of linkselect to be sent back to the this.href property. Do this by using the return statement, which sends a value back from a function call, as shown here:

return linktext;


This return statement causes the function to return the value of linktext, which is the randomly picked URL that picklink() chose. Add the return line inside the picklink() function in place of the last document.write() line.

The Completed Exercise

If you examine the completed text for this new HTML document, which follows, you'll notice that it's similar to Exercise 13.1, except for the removal of the inline <script> tag and the replacement of document.write() with a return statement.

<html> <head> <title>Random Link Generator</title> <script language="JavaScript"> function picklink() {  var linknumber = 4;  var linktext = "nolink.html";  var linkselect = Math.floor(linknumber * Math.random()) + 1;  if (linkselect == 1)  {   linktext = "http://www.netscape.com/"  }  if (linkselect == 2)  {   linktext = "http://www.lne.com/Web/"  }  if (linkselect == 3 )  {   linktext = "http://java.sun.com/"  }  if (linkselect == 4)  {   linktext="http://www.realaudio.com/"  }  return linktext; } </script> </head> <body> <h1>My random link generator</h1> <p>Visit a <a href="dummy.html" onClick="this.href = picklink()">randomly selected</a> site from my list of favorites.</p> </body> </html>


Task: Exercise 13.3. A Random Link Generator Using an Array

The only problem with the preceding example is that you need to keep adding if tests for each new link that you want to include in your list of favorites. To get around this difficulty, and to streamline the appearance of the script considerably, there's a JavaScript mechanism that enables you to create lists of variablesor arrays.

An array is a list of values associated with a single variable. For example, an array called mylinks[] can contain a list of all the links used by the picklink() function. The value of each link in the list is then referenced by a numeric value inside the square brackets, starting with 0: The first variable can be found with mylinks[0], the second with mylinks[1], and so on.

Before you can use an array, you must first construct it. The easiest way to do this is to just make an empty array by calling the Array constructor with no argument, like this:

mylinks = new Array();


You can then populate each of the elements individually:

mylinks[0] = "http://www.netscape.com/"; mylinks[1] = "http://www.lne.com/Web/"; mylinks[2] = "http://java.sun.com/"; mylinks[3] = "http://www.realaudio.com/"; mylinks[4] = "http://www.worlds.com/";


The elements of the array are created automatically when they're referenced. When the array is constructed, it contains no elements. You add five elements when you reference them by assigning values to them. Let's look at what happens when you skip some indexes when assigning elements in an array:

mylinks = new Array() mylinks[0] = "http://www.netscape.com/"; mylinks[4] = "http://www.worlds.com/";


This array still contains five elementsthe elements with indexes of 1, 2, and 3 are just empty. The size of an array is dictated by the highest index referenced in that array, regardless of whether you've referenced all the indexes before the highest index.

You can skip the step of assigning each of the array indexes individually by simply passing a list of elements to the array constructor when you call it, like this:

mylinks = new Array("http://www.netscape.com/",           "http://www.lne.com/Web/",           "http://java.sun.com/",           "http://www.realaudio.com/",           "http://www.worlds.com/");


When you use this method of construction, the mylinks array is prepopulated with the five elements that you passed to the Array() constructor as arguments.

You can then fill the mylinks array with values by assigning them as you would any other variable. For example, in Exercise 13.2, you can add code to the <script> section that creates an array with the number of links and then stores those link names into that array. Here's an example of an array with five elements, with a URL assigned to each:

mylinks = new Array("http://www.netscape.com/",           "http://www.lne.com/Web/",           "http://java.sun.com/",           "http://www.realaudio.com/",           "http://www.worlds.com/");


With a list of URLs defined, you can modify the original picklink() function so that it selects a link by choosing from those included in the array instead of by using a number of if tests. The following is the new code for picklink():

function picklink() {  var linkselect = Math.floor(Math.random() * mylinks.length);  return (mylinks[linkselect]); }


As you can see, this function is much smaller than it was previously. Obviously, the fact that we moved the list of URLs out of the function helped, but we economized in other ways as well. Arrays have a property called length that contains the number of elements in the array. Instead of creating a variable called linknumber and manually entering the number of links available, we just grab the size of the array and plug that into the random number generator. Because the size of the array is 5 and the elements are numbered 0 through 4, we don't need to add 1 to the random number that we generate to get things to work properly. When I've got a random number, I return the array element with that number as its index.

We can also consolidate the picklink() function further by removing all the work variables and performing all the math inside the return statement, like this:

function picklink() {  return mylinks[(Math.floor(Math.random) * mylinks.length))]; }


The Completed Random Link Script with an Array

The following code shows the final version of the script, which incorporates all the changes we've made in this exercise, including the MakeArray() constructor function, the creation of the array of links, and the modifications to picklink().

<html> <head> <title>Random Link Generator</title> <script language="JavaScript"> var mylinks = new Array("http://www.netscape.com/",             "http://www.lne.com/Web/",             "http://java.sun.com/",             "http://www.realaudio.com/",             "http://www.worlds.com/"); function picklink() {  var linkselect = Math.floor(Math.random() * mylinks.length);  return (mylinks[linkselect]); } </script> </head> <body> <h1>My random link generator</h1> <p>Visit a <a href="dummy.html" onClick="this.href=picklink()">randomly selected</a> site from my list of favorites.</p> </body> </html


Tip

To add new links to your list, just add them to the list of arguments to the array constructor.





Sams Teach Yourself Web Publishing with HTML and CSS in One Hour a Day
Sams Teach Yourself Web Publishing with HTML and CSS in One Hour a Day (5th Edition)
ISBN: 0672328860
EAN: 2147483647
Year: 2007
Pages: 305

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net