| Previous Topic | Tutorial Table of Contents | Next Topic |
Generalized Functions and JS Librariesfunction addNumbers(form) {
Such a function would be written for a web page with three textboxes (or textareas), called input1, input2 and output. In other words, this script is specific to such a page and could not be used with other pages that lack three textboxes (or textareas) or that name them something different. JavaScript (1.1 and 1.2) allows you to create a library of generalized functions, store them in a separate file (called a .js file) and call that file from any particular web page you write to use the functions in it. How to create and use a .js file is explained below. How might we write a general function to replace the above addNumbers() function? Here's how: function addAnyNumbers(a, b)
{
Instead of accepting just a form object, the function now receives the two numbers to added. How to use this type of general function may be unclear until you see it in the context of an html page that calls it: <html>
<body bgcolor="#ffffff">
To see if this script really works, click here. The power of this approach is that you could use this function for any of your pages that need to add two numbers. This would be especially helpful if the function did a number of complicated things, such as data entry validation. However,
you would still have to cut and paste this script into every page you write
that uses it. We can be even more economical than that by . . .
In programming parlance, a library is a set of files with executable code that can be called on from a working program (in this case, a html page). JavaScript library files can contain JavaScript functions that are needed on many of your web pages. By putting them in a library file, you only have to write them once and can call them in as many subsequent programs as you want. Another
very important advantage is that if you need to change what the
function does or you found an error in it that needs to be changed, you
only have to edit one file, not every single clone of it.
1. The library file can contain only JavaScript code -- no html tags, including no <script> tags. 2.
The library file must be saved as a text file with a .js extension.
In the header, write: <script language="JavaScript"
src="scriptName.js">
where scriptName is the name of the external library file. The URL specified in the src attribute can be either an absolute or a relative URL. Note also that a closing </script> tag is required, even though there is nothing between the script tags. |
| Previous Topic | Tutorial Table of Contents | Next Topic |