[Back to

 previous page] [Next Page

 in Series]

Ken Ward's Java Script Tutorial ...

Using an array to write your table of contents

After a while, our contents page gets rather long and it can be a hassle keeping it in order. This is especially true when we we also use this information in the navigation system. So when we make certain changes we have to change the contents page and all the navigation (previous, next buttons, etc) and this can be a problem when we are limited in time.

The following is written by Java Script (except the table):

I have only used a few pages in the example so that the code is easier to understand. The code is in a js file called ArrayToContents.js.

We put this in the page by writing the following code in the HEAD of the page:

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




This loads all the stuff in the js file. I have used a js file because in a real application we might use the data in this file for various purposes such as writing the navigation, etc. By having a central source of this information, all we need to do is to update this information in one place and our site is updated all in one!

You can see what the js file looks like here.

To get the table of contents written in our page we put the following code in the page:

<script type="text/javascript">





The js file contains two arrays (that is, it uses parallel arrays, because the items in each array refer to the corresponding items in the other array). These arrays (shown below with only a few items, to stop the amount of data confusing us) are:

databas1=new Array("index.html","alerts.htm","alertsText.htm","alertsImages.htm","jumpfunction.htm");

//We create an array to hold the names of the files

databas2=new Array("Contents of JavaScript","Message Boxes","Alerts from Text","Alerts from Images","Hyperlink Function");

//Then we create an array to hold the descriptions of the files

Each array, databas1 and databas2, contains corresponding items. The filenames (relative) are contained in the first database, and the titles are contained in the second one. To update the arrays, it is simply necessary to add a filename in the position you want it in and the title of the page in the corresponding position in the other database. This makes updating much easier.

The function, ContentsWriter() is in the js file. It writes the table of contents:

function ContentsWriter()
document.write("<h2>My Contents Page</h2><p>");
for (var x=0;x<NumberOfFiles;x++)
document.write("<a href="+databas1[x]+">"+databas2[x]+"</a><br>");

This is a very simple function that writes a list of links, using the arrays to provide the necessary information.

You can add what formatting you care to, of course!

Ken Ward's HTML Guide...