Tutorial 1 - Basic Display

Index - Tutorial 2 - Objects,Events&Functions

This is the first of a series of tutorials which will help you to add interactivity to your HTML documents by using JavaScript. These tutorials assume a working knowledge of HTML 4 and of CSS style as well as a commitment to validate all code including stylesheets.

Javascript documents should always be written to the language standard set by ECMA. One of the best ways of checking your work is to use jsLint. Just cut and paste your script into the input box and press the jsLint button. Either you will get an 'ok' message or an easy to interpret message including line number on any problem. Code that checks with jsLint will be less likely to be quirky in any of the modern browsers.

In each of the following JavaScript tutorials any text that is displayed in green can be cut and pasted (aka ripped) into a new HTML document template (ie. complete with doctype, head, title and body elements) and viewed with your favorite browser. You may prefer to type in the example yourself just so that you can review your understanding of each line as it is entered. Choose a strategy which works for you and have some fun learning about the power that JavaScript gives to web page designers.

A Standard JavaScript Template

Start by making a template file [eg. jstemp.htm] or setting up a macro in your text editor that contains the following code:

<script type="text/javascript">
//<![CDATA[

//]]>
</script>

The first line creates an HTML element which tells your browser that what follows is in a scripted language and this time it is JavaScript (not VBScript or JScript). The next line marks it as unparsed character data. Otherwise characters like & and &lt; will be treated as start of character entities (like &nbsp;) and tags (like <b>) respectively. A comment mark is used so that JavaScript doesn't try to interpret CDATA. The next line (ie. the blank one) is where your JavaScript will be inserted. Finally both the CDATA and script elements are closed in the normal HTML manner.

NOTE: It is recommended that you write code that assumes that some users may not have JavaScript enabled browsers or have temporarily turned it off. This is part of the 'Be kind to ALL users' philosophy. HTML provides an element specifically for this purpose. Make a template (or macro) of the following so that it can be included easily in the body section of every document that has a script element.

<noscript>NOTE: Your browser does not support JavaScript
    or support has been turned off. Too bad!</noscript>

The message between <noscript> and </noscript> will appear on a non-script enabled browser or one with scripting turned off. The noscript element must be placed in the body section of your document to be valid HTML 4!.

Where Is JavaScript Placed

JavaScript is similar to style property rules in that it can be placed in one of several locations depending on how often the code is needed.

Short examples or trivial 'snippets' (such as many in this first tutorial) can be placed inline (sometimes called on-the-fly). These are inserted (with the above template) into the body section of a document.

Most JavaScript utilities are placed in the head section of a document. This assures that they are loaded immediately and that if appropriate can be used in several places in the document.

Just as stylesheets can be in separate files for access from many documents, JavaScript routines can also be isolated to separate files for reuse by several documents. Isolation also prevents html validators from signaling false errors inside javascript.

And finally JavaScript can be invoked or started from within element attributes by using the javascript: keyword.

The best choice is to first develop and 'debug' scripts within the head element. This saves time switching between files. When the script is working well, then cut and paste it to a separate file for reuse. To link to these files, the script element changes to include a 'src' attribute but no content between the tags. For example:

<script type="text/javascript" src="mtmtrack.js"></script>

NOTE: It is a long standing tradition for these external files to use the extension .js but it is not a requirement.

'Hello World' Example

A common first programming assignment in many languages is to write the greeting 'hello world' to the screen. This will give you the chance to become familiar with your text editor and the development process as well as some basic JavaScript syntax.

<script type="text/javascript">
document.writeln('hello world!');
</script>

document.writeln('hello world!'); may seem trivial but it has many points of interest that should be thoroughly understood. The word document indicates one of the major objects in JavaScript. The complete list of available JavaScript objects are given in the Appendices In this example document is used to direct data into an HTML document for display. The following dot indicates that a method or operation is to be applied to that particular object. In this example the method is writeln(). Brackets indicate a parameter or value to be used by the method. Inside the bracket is a quoted string value to be used as is. Matching double quotes may also be used but there are many situations where double quotes conflict with HTML attribute assignment so single quotes are preferred. Finally, the sentence known in programming as a statement) ends with a semicolon. There is another method called write() which is almost the same as writeln() but does not display a new line after the parameter value. New lines can be forced in JavaScript with the \n newline escape sequence.

Alert, Prompt and Confirm Windows

JavaScript has three very simple ways of providing the user with information and possibly feedback through the use of popup windows. window.alert() is a window object method which displays a message but no feedback can be gathered from the user. There is only one string parameter.

<script type="text/javascript">
window.alert('hello world!');
</script>

The method window.prompt() displays a standard dialog which allows the user to enter data. Note that there are two strings, separated by commas as parameters. The first parameter is a prompt message. The second parameter sets the default value of the entry. It is normally blank but is required to give a blank input line in the MSIE browser.

<script type="text/javascript">
window.prompt('Please enter your name: ','');
</script>

The method window.confirm() displays a standard dialog which allows the user to respond with either ok or no. The parameter is a prompt message.

<script type="text/javascript">
window.confirm('Shall we continue ?');
</script>

Interactive 'Hello World' Example

To improve a bit on the basic 'hello world' example and to show how JavaScript can introduce interactivity with the user, let's prompt for the user's name and then use it in our display.

<script type="text/javascript">
name="";
name = window.prompt('Please enter your name: ','');
document.write('hello '+name+ ' !');
</script>

name=""; introduces the concept of a variable which is a temporary data holder. Variable names must begin with a letter, contain only alphanumeric characters and underscore, and are case sensitive. Appendix - Reserved Words list words with special meanings that cannot be used as variable names. The Core Language tutorial has more details on variables, operators and statements.

After the data is entered using the prompt method, it is stored in the variable called name. It is then appended to the message 'hello ' and displayed on the screen. Note that an alert window could also have been used for the display.

Last Update and Current Date Examples

The first snippet demonstrates a useful script to tag your web pages with the lastmodified property of the document object. Many authors hard code the file date into the text but forget to update it when the page changes. Why not let the browser do the work for you?

<script type="text/javascript">
document.writeln("This page updated on " + document.lastModified);
</script>

This page updated on Fri, 14 Oct 2005 20:35:30 GMT

The next example introduces the built-in system object called Date. A copy of the object called todays_date is created and then printed. For more on objects and how they are created refer to Objects, Events and Functions. For a complete listing of system objects refer to ECMA Core Objects.

<script type="text/javascript">
todays_date=new Date();
document.write("Current Date/Time is ");
document.writeln(todays_date);
</script>

Current Date/Time is Fri Nov 25 2005 00:18:38 GMT+0100

Using the Status Line

Writing a message on the status line using the status property of the window object is just as easy as calling an alert window and is less intrusive. This sample script must be placed in the head section as it uses two user defined functions (one to display a message and the other to reset the status line). Functions are explained in the Objects, Events and Functions tutorial. To start the display function the onLoad event is referred to by the body element (eg <body onLoad="showStatus()">). Events are discussed in the Objects, Events and Functions tutorial.

<script type="text/javascript">
function showStatus() {
   window.status = 'hello world!';
   change2 = setTimeout("xit()",10000);
   }
function xit() {
   window.status = "";
   }
</script>

NOTE: You should avoid using the status line unless necessary for your application. Many readers rely on access to the status line for observing link addresses. One way around this issue is to clear your use of the status line after a fixed amount of time delay as this example shows. setTimeout() is a window object method that transfers control to the xit function after 10 seconds (the second parameter [ie. value in brackets] must be given in milliseconds). Because the setTimeout() method is only defined for the window object, you need not use its full name [ie.window.setTimeout()].

Popup Windows

New windows can be popped up over the top of the existing window by using the window object open() method. Open has three parameters in the order of URL, windowName, [featuresList]. To make sure underlying screens are retained, the window must be opened in a user defined function! To popup a short info blurb you can use:

[script component - placed in document head]
<script type="text/javascript">
function openWindow(url,name,w,h,l,t) {
features='dependent=1,width='+w+',height='+h+',left='+l+',top='+t;
popupWin=window.open(url,name,features);
if (!popupWin.opener) {popupWin.opener = self;}
}</script>

[html component]
<a href="javascript:openWindow('linuxreg.txt','InfoWindow',200,300,400,75)">
Get Info</a>

Note: The window object is very browser specific and any use must be thoroughly tested in all anticipated client browsers. This simple example shows many differences between browsers:

  • Opera: Positions well and automatically adds scrollers when needed.
  • Netscape: Positions well but no scrollbars with large content.
  • Slimbrowser: Doesn't size or position well!

Index - Tutorial 2 - Objects,Events&Functions

Copyright (c) 2005 by John W. M. Russell