Ken Ward's Java Script Tutorial ...

Back and Forward Buttons (New)

On this page:

  1. Finding Which Page is Current Using Substring
  2. Find Element in Array

The previous back-forward code using a js file seemed all right when developing a site, but soon became annoying when it was necessary to update the site. When a new page was placed in the middle, then it meant updating all the following pages. As programming is about being lazy and getting the computer to do the work, I had in mind changing this code to something easier to use. This page is the latest in a series:

  1. Back and Forward Using History
  2. Back and Forward Buttons (Simple)
  3. Back and Forward Buttons
  4. Back and Forward Buttons 2 (This Page)

The resulting code had to:

The code was actually worked out quite logically (rare for me) so it is explained pretty well by looking at the code.

All we now need is to call the js file in each page. We do this with:

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




And we put this somewhere in the head of each file.

Finally, we put code around our images:

<a href="javascript:goBack()">

<img src="BackArrow.gif" alt="Back" />


<a href="javascript: goForward()">

<img src="ForwardArrow.gif" alt="Forward" />


And our pages will update themselves whenever we move the files around in the list which we called database! Note: image tags require an "alt" attribute for XHTML.

Finding Which Page is Current Using Substring

The current page is found with the following code:

//from this string using lastIndexOf:





The current page is found to be location.href, which is the full URL. You can click here to see the "location.href" of this page. The pages in the array are relative filenames, and mainly contain only the filename, and not the path. So, we need to extract the filename from the full URL. For this, we use substring. This has the form substring(startPos,endPos) and copies everything in the string starting at startPos, and ending at endPos. We find the start pos using:


As we don't want to include the "/", we add one to start after this (which is where the filename starts, of course). The last point we want to copy is the end of the URL, which is:


So now we can compute the filename with:


Find Element in Array

So having found the filename, we can check if it is in our array as follows:


//Now we look through to list to find our file, and

//therefore, its number in the list:

for (var i = 0; i <= n; i++)


if (database[i]==ThisFilename)






Ken Ward's HTML Guide...