Basic JavaScript

Introduction

Javascript is Netscape's proprietary addition to the design of WEB pages. It is called a subset of Java, but it is more properly called a superset of HTML, for it is the means by which Netscape permits WEB page designers to write HTML on the fly in response to user interaction with their pages. The bad news is that Javascript is a programming language. The good news is that many of its features, because they are grounded in HTML, can be easily exploited by the casual WEB page author, who knows little or nothing about programming.

First, because it is based upon HTML, Javascript follows the conventions of HTML page construction. Javascript is integrated into the HTML tag set, and it can be added to existing pages without much effort. In the event that the browser accessing the page does not understand Javascript, as with Microsoft Internet Explorer versions prior to 3.0 and Navigator versions prior to 2.0, the Javascript is ignored and the page can be loaded and viewed without error, assuming that an alternative to the Javascript is provided. Indeed, Javascript allows the page author to poll the browser to determine if Javascript is enabled, thereby permitting the author to build an alternative page or HTML code fragment which will be used automatically should Javascript not be available in the browser.

Second, unlike Java, which requires that classes be downloaded to the client computer, all of Javascript is built into the Navigator browser (or added on to the IE browser on the client computer), so that transmission of the Javascript is relatively painless and swift. The overhead in RAM for Javascript is lower than for Java, because there is no need for a virtual Java machine in which to run the code. On the other hand, because Java applets are compiled, but Javascript is interpreted, Javascript programs must be read and interpreted before being executed by the computer, slowing performance relative to Java. In actual practice, however, because there is less to download similar effects in Java and Javascript will probably exhibit similar speeds of execution.

What We Will Do With JavaScript

1) Open a Document in a New Browser Window

2) Use the Browser Status Line as a Help/Hint Line

3) Use the Confirm Dialogue to Obtain Confirmation of an Action

And there is a bonus command that you will find if you pay attention.

Some Preliminaries

Before we insert our JavaScript routines in our HTML document, it is necessary to do a bit of preparation of the HTML. These preparations will insure that browsers which cannot process JavaScript (Navigator releases earlier than 2.0 and MSIE versions earlier than 3.01, Mosaic, etc., and browsers in which JavaScript support has been disabled) will be able to use the standard HTML of your WEB page without error. If this preparatory work is not done, non-JavaScript browsers will either print the JavaScript code on the WEB page as though it were part of the text of the page or return errors.

The first thing that you ought to do is to insert the <SCRIPT LANGUAGE> tag into the HTML of your document. This tag alerts the browser that the document uses a Scripting language (either JavaScript or Visual Basic). It is not absolutely necessary, and the browser will default to the installed SCRIPT engine if no language is defined, but it is good programming practice, The tag looks like this:

<SCRIPT LANGUAGE="JavaScript">

The tag should be placed within the HTML <HEAD> portion of the document, after the <TITLE></TITLE> tags. The <SCRIPT> tag and its modifiers also can be used within the body of the WEB page document. You can use as many SCRIPTS as you like, but it simplifies things to keep as much of the JavaScript code as possible in the <HEAD> portion of the document. Some methods in JavaScript, such as the document.write method, must be in the body of the document if you want to place text in the onscreen document.

<HTML>
<HEAD>
<TITLE>JavaScript Demo</TITLE>
<SCRIPT LANGUAGE="JavaScript">

The second thing that you need to do is to hide the JavaScript from non-JavaScript browsers. You do this by placing the actual JavaScript code within HTML comments. Comments are recognized as non-printing matter by browsers and will be passed over by non-JavaScript browsers. JavaScript-enabled browsers, however, will be able to use the JavaScripts, even though they are marked as comments. Therefore, you want to create a multiple line comment section following the <SCRIPT> tag, thus:

<SCRIPT LANGUAGE="JavaScript">
<!-- (This tag marks the beginning of a comment)
//--> (This tag marks the end of a multiple line comment)

Now, you can use the comment section created with the above tags to conceal the JavaScript: simply place all of the JavaScript commands within those comment tags.

Lastly, you ought to provide a graceful exit for those browsers that do not support JavaScript. Adding a <NOSCRIPT> tag allows a non-JavaScript browser to display a message to the user that JavaScript is required.

<NOSCRIPT>
This page requires a browser with JavaScript. An alternate page
without JavaScript is available at:
<BR><A HREF="http://www.domain.com/altpage.html"></A>
<P>
If you are using Navigator 2.0 or later and you see this message, you
need to enable JavaScript.
Choose Options|Network Preferences, choose the Languages tab, and
click Enable JavaScript.
</NOSCRIPT>

With those preliminaries out of the way, we can move on to the actual JavaScript.

Cloning a window

1) Open a Document in a New Browser Window

One of the more useful JavaScript commands allows you to direct the browser to open a document selected by the user in a cloned browser window, rather than to use the primary window for the new document. This permits the original window and its contents to remain open and accessible while the new window displays the second document. The user can then return to the original document without using the Back button (or selecting the previous document from the History in the Go Menu), simply by clicking in the original window. This provides faster navigation for the user by eliminating the reloading of the document to recover the original navigation menu. There are two ways in which this new window can be created. The first is to use the HTML OPEN command and to specify a TARGET window that does not exist. The browser will then create a window to receive the specified documnet, giving it name used in the TARGET specification. But this is a JavaScript tutorial.

JavaScript provides two methods to cretae a new browser window. Both are based upon the aforementioned HTML method. The first way, and the one most frequently seen, is to create a form in which there is a menu or list of pages from which the user makes a selection and which includes a button or buttons on which the user clicks to actually make the selection. While forms are now standard HTML and have a certain appeal, they are best used for their original purpose, the submission of data, rather than for navigation. Besides, the introduction of a form would probably require you to redesign your WEB page or, at the least, to rewrite your page to include a lot of extra HTML. However, if you want to use JavaScript and want to permit the users of early versions of Microsoft Internet Explorer to use the page, there is no alternative to the use of forms, The Microsoft implementation of JavaScript, called JScript, is not compatible with the Netscape version in all respects and cannot execute many of the methods (commands) of JavaScript in the manner defined by Netscape. MSIE cannot process some methods of JavaScript if they are placed within the <HEAD></HEAD> tags. Such methods will work only if placed "inline", embedded in the actual HTML which calls them. Among those methods is the window.open method. Therefore, to allow MSIE to use your page, you must embed the JScript within your menu, creating one button for each item in the menu. The code looks like this:

 

<FORM NAME="Form1">
<INPUT TYPE="button" NAME="Button1" VALUE="NetPage"
onClick=window.open("NetPage.html","window1">
</FORM>

This produces a button with the onscreen label "NetPage", which, when clicked, opens that document in a new window named "window1". (It is a good idea to name new windows.) Each item in your menu will require a separate button. Just cut and paste the same code to make the requisite number of buttons, changing the VALUE attribute to echo the page TITLE. Increment the NAME attribute for each successive button, or name them as you desire. If you prefer, the NAME attribute can be omitted, because the browser will keep an array of the buttons stored in memory anyway. The NAME attribute merely allows you to refer to a particular button by name rather than it's array position. (Do not change the window's name, however. Using the same window.name property for each button will cause subsequent documents selected from the menu to open in the same window rather than in superfluous new windows.)

(Note, besides the irregularities that exist between Netscape Navigator and Microsoft Internet Explorer and JavaScript-conversant browsers and non-Javascript browsers, there are some differences between the way that the Mac and the Windows versions of the browsers react to HTML and JavaScript. For instance, the Mac versions of Navigator prior to 4.0 will not properly process the VALUE attribute of a button created in a FORM. The Windows Navigator will permit the changing of the VALUE attribute by a function. Although this is minor, however, you should be aware that discrepancies exists.)

If, on the other hand, you do not care whether MSIE users can view the page (you have written an alternate page, of course), then you can use a simple modification of your existing page to accomplish the same end. The method which I use and recommend requires that you write just three new lines of code and make one minor change to your existing HTML.

In all likelihood, your index WEB page already contains a menu (a bulletted unordered list) of hypertext linked URLs that lead to the various pages on your WEB site. When the user clicks on the hypertext link, the browser requests the page that is located at the address specified by the URL. Each hypertext URL has the standard HTML anchor format:

<A HREF="http://www.domain.com/netpage.html">NetPage Name</A>

Clicking on the hypertext link loads the page into the active browser window, replacing the page already there. By making the following simple modifications, you can use the same hypertext link format to cause the requested page to open in a clone window. (In addition, you can control the look of the window, but that is more than we are attempting here.)

First, you must create a JavaScript routine that will open a clone window with the window.open method. Rather than merely inserting this into the HTML repeatedly for every menu item as you would for MSIE, you can write one custom, reusable routine and place it in the comments section of the <SCRIPT> tag in the document head. Thereafter, whenever you want to open a document in a new window, you simply call the generic routine and pass the document's URL to it, and the routine performs the window.open command with the appropriate document. Therefore, write the following JavaScript code:

 

function newWindow (str) {
cloneWindow=window.open(str,"brwsrWindow")
}

This routine will cause the document requested by the variable "str" to be opened in the window with the names"cloneWindow" and "brwsrWindow, if the window already exists, or it will create the window if it does not exist. (Windows can have two names. The first above, "cloneWindow", is used to refer to window properties, while the second, "brwsrWindow", is used in URL references to the window.) In order to call the routine, however, you must create a JavaScript "handler".

JavaScript has some simple commands that can be used by anyone who possesses even a nodding acquaintance with HTML. Among them is the very powerful JavaScript URL, a variation of the standard HTML URL. The JavaScript URL can contain any JavaScript command or function (even user-defined functions such as our newWindow routine), and the syntax is almost identical to that of the Hypertext anchor URL.

To use the newWindow routine we have only to modify the standard anchor URL by the addition of the word "javascript" followed by the name of the function, thus, the standard anchor:

<A HREF="http://www.domain.com/netpage.html">NetPage Name</A>

is modified to look like this:

<A HREF= javascript:newWindow("http://www.domain.com/netpage.html")>
NetPage Name</A>

(Note the parentheses. Also, the quotation marks are mandatory.)

The entire HTML for the page will look like this:

<HTML>
<HEAD>
<TITLE>JavaScript Demo</TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!--
function newWindow (str) {
cloneWindow=window.open(str,"brwsrWindow")
}
//-->
</SCRIPT>
</HEAD>
<BODY>
<A HREF=javascript:newWindow("http://www.domain.com/netpage.html")>
NetPage Name</A>
</BODY>
</HTML>

This will produce a link to the same page as the simple hypertext URL, but the document will now be opened in a second window rather than in the original browser window. It is that simple.

Hints in the Status line

 2) Using the Status Line as an Help/Hint Line

Status is a property of browser windows. The Status line appears in the bottom border of the browser window. It is used normally to display the URL address when the mouse cursor passes over an hypertext link or to show the connection progress as the browser contacts an address and transfers data from the server to the browser. There are two types of status, the defaultStatus, which appears when there is no activity in the browser window, and the window.status, which replaces the defaultStatus in response to events in the window, e.g. when the mouse cursor passes over a link. When the event is completed, the defaultStatus message is re-displayed (in Navigator, but not in MSIE). Using this attribute, you can provide the user with information about a link rather than the mere URL of the link.

As with the previous example, you must create a JavaScript routine that will set the defaultStatus and/or window.status. In the comments space of the document head, enter the following JavaScript (with your own hint):

function statusHint() {
window.defaultStatus = "Click the Question Mark Icon for Help"
window.status = "Help for this page"
}

Next, in the <BODY> of the document, go to the anchor hypertext reference for which you want to supply the transitory status hint:

 

A HREF="http://www.domain.com/netpage.html">
<IMG SRC="question.gif" WIDTH=X HEIGHT=Y>NetPage Help</A>

 

and modify it to resemble this:

 

<A HREF="http://www.domain.com/netpage.html"
onMouseOver = "statusHint(); return true">
<IMG SRC="question.gif" WIDTH=X HEIGHT=Y>NetPage Help</A>

Note that the handler must return the value "true" to the function.

This can be done for more than one link by embedding the necessary hints in the HTML and passing them to the statusHint routine as a variable, as in:

 

<A HREF="javascript:alert('hi there')"onmouseover="statusHint
('This link executes an Alert.');return true">Click me to see a
message.</A>

This will require that the status hint function be modified to permit a variable that will redefine the hint, thus:

 

function statusHint(hnt) {
window.status=(hnt)
}

(Note, that you cannot execute two user-defined functions in a JavaScript URL. Using the newWindow function and the statusHint function will result in only the newWindow function being executed, and no custom status message will be displayed.)

Also, when you define a custom defaultStatus message, be aware that the message will persist in the user's browser when other pages are loaded. Therefore, you should either redefine the defaultStatus for every page or select a message that is pertinent to all pages at your site. Finally, in order that your custom defaultStatus message does not persist in the user's browser after an external link has been accessed (thereby exiting your site), you should include a routine by which the defaultStatus is reset to a null value when the user leaves. This requires use of the JavaScript event triggers onLoad and onUnLoad. The code looks like this:

 

<BODY onLoad="dfst('Click the Question Mark icon for Help')";
onUnLoad="dfst(' ')">

(Note that the events are placed within the actual BODY tag. The onLoad event operates immediately that the document has been parsed and the onUnLoad event operates when the document is replaced by another.)

The function that would be called by these events would look like this:

 

function dfst(dft) {
window.defaultStatus=(dft)

}

Confirm an action

3) Use the Confirm Dialogue to Obtain Confirmation of an Action

JavaScript has a built-in function, the CONFIRM, which allows the page designer to require the user to give consent to an action that is about to occur. The CONFIRM window is a dialogue box in which there are two buttons and a custom message. The buttons give the user the choice of accepting (Yes) or declining (No or Cancel) the proposed action. The CONFIRM returns True or False, depending upon the button clicked, and the JavaScript routine then acts based upon that returned value. Typically, the JavaScript function will contain an IF...ELSE conditional routine that will execute the statements following the IF when the returned value of the CONFIRM is true, or the statements following the ELSE when that value is false. A simple use might be to confirm that when the user has clicked on an external URL, that the user truly wishes to exit the site. The URL would use the now familiar JavaScript URL and would look like this:

 

<A HREF="javascript:exit("http://www.domain.com/netpage.html")>
NetPage Name</A>

While the function exit() would look like this:

 

function exit(addr) {
if (confirm("Are you sure that you want to leave?"))
location.href=(addr)
else
location.href=history.go(0)
}

 

(This function accepts the variable "addr" from the calling handler (the JavaScript URL) and passes it to the window.location.href property if the user clicks the "Yes" button. If the user clicks the "No" or "Cancel" button, then the function simply reloads the current window.history property as the location.)

The CONFIRM has other uses, of course, such as confirming data entered into a form. The reader can find out about this and other JavaScript features at the Netscape site <http://netscape.com>. JavaScript is a rich programming language with many uses. It can require intense study and some trial-and-error, but these few simple examples can be used by anyone who has a text editor.

(Did you find the bonus JavaScript object?)

©copyright 1998 Horace W. LaBadie, Jr.

Tech Bits page   EDA