If you've been creating a JavaScript Library, you can now put the final touch on your library's JavaScript navigation.
If you haven't been creating a Library, review the directions at the bottom of the
Introduction to Arrays page and
Looping through your Library's Script Array before continuing here.
Using any one of several string methods you learned in Tutorial 8, you can extract the file name of the page currently loaded in the browser.
With that information, you can now compare that value with your script array elements to find a match. When a match is found, your script sets the location equal to either the previous element's value or the next element's value, depending which function you are in - nextPage() or lastPage().
You will be replacing "location.href" in the for loop's if statements contained in the nextPage() and lastPage() functions with a variable representing the extracted file name. Here is one way to accomplish that:
var pageNameStart = location.href.lastIndexOf("/")
var pageNameEnd = location.href.length
var currentPage = location.href.substring(pageNameStart+1,pageNameEnd)
There are probably a zillion ways to extract the file name of the currently loaded page, and you should construct the file name extraction the way that makes most sense to you and the way that fits your array construct.
Then, change the reference of "location.href" in the for loop's if statement to the new variable representing the extracted file name:
function nextPage() {
for(var i=0; i<myScripts.length; i++){
if(myScripts[i] == currentPage) {
location.href = myScripts[i+1]
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] == currentPage) {
location.href = myScripts[i-1] // set the location equal to the previous element's value
break
}
}
}
If you haven't placed a call to these functions in each of your library's files yet, you will beaten at sun up. After the beating, you may place calls to your functions in each of your files like so:
<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>
And there you have it - page to page navigation all powered by JavaScript. If you are having trouble getting yours to work, check all your variable names, use the NN JavaScript console, ask a friend, take a break, and do everything else mentioned in the
trouble shooting tips.
Just don't email me. Remember - ya gotta learn to trouble shoot!!! You are nothing if you cannot trouble shoot.