This isn't a lesson as much as it's a tidbit of information that can be useful. It reveals to you how to have a JavaScript program running on a separate file that can be accessed by any page. The only thing that you have to do differently than usual is in the JavaScript script tag. Add the src="file_url" modifier into it.
I used to use this functionality on my nav bars, but I've since moved on to bigger and better (and easier) things. However, if you don't want to use any server side scripts, using a separate JavaScript file is right up your alley.
OK, so the file should be named "anything.js". Then whenever you want to access that file, you just add in the src modifier, which points to that file, like this:
<script language=JavaScript src="teacher/anything.js"></script>
As with any URL, it can be relative or static. That is, it can point to the file from the current folder, or it can point to it from the root folder of your web site. It doesn't matter which you use.
But that isn't everything. All you have to put into the .js file is the code itself - just as if you were putting it inside of the script tags. You can do anything you can normally do in JavaScript in this file, and that includes modifying form elements on the web page itself. As far as the browser is concerned, the code in that file is in between those script tags on the web page.
Another note that had me stumped the first time I did this is that any and all quotes in your HTML tags within that file that you are going to display on the web page must have a before them. Here's an abridged example of the (old) right nav bar on the site:
dislinks();
function dislinks()
{
var links = new Array
(
"<br><hr><b>Learn HTML</b><hr>",
"<a href="xxx">HTML Lesson Index</a><br>",
"<a href="xxx">Tags</a><br>",
"<br><hr><b>Learn JavaScript</b><hr>",
"<a href="xxx">JavaScript Lesson Index</a><br>",
"<a href="xxx">Variables</a><br>",
"<br><hr><b>Supplemental</b><hr>",
"<a href="xxx">Good Formatting Practice</a><br>"
);
for( var i = 0; i < links.length; i++)
{
document.write(links[i]);
}
}
As you can see, I first store the elements in an array, and then I display that array. The xxx's are to save space-just replace them with whatever URL you're using. So each element of the array must contain all of the HTML formatting and links that the text will have to have. You have to put a slash prior to the quotes because each member of the array is completely surrounded in quotes. Without the slash, the script thinks that is the end of the element, and it messes everything up. You could concievably use single quotes instead of the slash+double quote combination, but I opted for the slash for no reason in particular.
And there you have it! As far as I can tell, this will be the last lesson in the JavaScript tutorial. I hope you've enjoyed it - but mostly I hope you've learned from it.