If you've been creating a JavaScript Library, begin to prepare your library's JavaScript navigation using a for loop. If you haven't yet created your scripts array but have been saving examples, review the directions at the bottom of the
Introduction to Arrays page before continuing here.
In the same external file containing your scripts array, create 2 functions; one called, "nextPage()" and the other, "lastPage()". These functions will contain looping statements that:
- loop through your scripts array
- look for a match between the page currently loaded into the browser and an array element
- set the location of the browser equal to the element value just before or just after the current element (depending on which function the loop is in, nextPage or lastPage)
- break out of the loop
The functions will not actually be used yet. They are missing a small piece from the string method section in Tutorial 8, but adding these functions will not cause an error in the pages linking to your source file.
The functions to place into your external JavaScript file are:
function nextPage() {
for(var i=0; i<myScripts.length; i++){
if(myScripts[i] == location.href) {
location.href = myScripts[i+1] //set the location equal to the next element's value
break
}
}
}
NOTE:
"myScripts" is used in this example, but should not be used in yours if you named your array something else. You should use the name you gave your scripts array. :-/
The lastPage() function is very similar:
function lastPage() {
for(var i=0; i<myScripts.length; i++){
if(myScripts[i] == location.href) {
location.href = myScripts[i-1] // set the location equal to the previous element's value
break
}
}
}
You should place a call to these functions in each of your current files and all future files as well. That way when you add the final touch to the functions, you will be able to navigate through your library immediately. Here is what I suggest you place in your files:
<form>
<input type="button" value="Last" onClick="lastPage()">
<input type="button" value="Next" onClick="nextPage()">
</form>
Or you could use regular links:
<a href="javascript:lastPage()">Last</a>
<a href="javascript:nastPage()">Next</a>
Starting to see where all of this is going? Just wait - it gets better!