HTML Markup | JavaScript | Java | Home & Links

Tutorial 1 - Basic Display

This series of JavaScript tutorials will help you to add interactivity to your HTML documents. JavaScript uses modern object oriented programming techniques to make it easier to program and reuse code. The tutorials assume a working knowledge of HTML/CSS and a commitment to validate all code including html, stylesheets and JavaScript.

In the JavaScript tutorials, text displayed in a blue box can be cut and pasted (aka ripped) into a new HTML document template (ie. complete with doctype, head, title and body elements). You may prefer to type in the example yourself to review your understanding of each line as it is entered. Choose a strategy which works for you and have fun learning about the power that JavaScript gives to web page designers. Script code for the tutorials' working examples can be found in jscode.js. Download or cut/paste what you need.

JavaScript Template

Several lines are always needed to separate your JavaScript code from the html markup in your document. To make coding easier make a template file or create a macro in your text editor that contains the following:

<script type="text/javascript">


The first line creates an HTML element which tells your browser that what follows is in a scripted language and should be interpreted using JavaScript. The next line starting with CDATA marks it as character data not to be interpreted by the browser. Otherwise characters like & and < will be treated as the start of character entities (like &nbsp;) and tags (like <b>) respectively. JavaScript programs normally use < and & quite often. 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 program will be inserted. Finally both the CDATA and script elements are closed in the normal HTML manner. CDATA sections always start with "//<![CDATA[" and end with "//]]>".

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. Sorry!</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!.

Warning: Unfortunately modern browsers such as FireFox, Opera and SlimBrowser do not display the contents of a noscript element when JavaScript has been deselected. Use CSS style visibility to solve this issue.

JavaScript Placement

JavaScript is placed in one of several locations depending on how often the code is needed.

  1. Short, trivial or one-time snippets can be placed inline (also called on-the-fly). These are inserted
    (with the above template) into the body section of a document.
  2. Most JavaScript routines 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.
  3. JavaScript routines can be isolated in separate files for reuse by several documents. Isolation also prevents HTML validators from signaling false errors inside javascript. My tutorials use this method.
  4. Javascript can be used in event handlers.
  5. JavaScript can also be placed within an element attribute where an URL is valid by using the javascript: pseudo-protocol. EXAMPLE. This can also be used to test snippets from your browser navigator bar!

The best choice is to first develop and 'debug' scripts within the head or body element. This saves time switching between files. When the script is working well, cut and paste it to an external file for reuse. To link to the external file, the script element (within the head) 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.

Example: 'Hello World!'

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

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

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 system objects available in JavaScript. The complete list of built-in system objects is 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. Another method called write() 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.

Note: While document.write() is a quick and dirty way to add content to a web page, it has a number of limitations on how it works and where you can use it. Programmers now write data into any element using the innerHTML construct.

Note: The CDATA construct is omitted from the short demos on this page as < and & are not used yet. But it could be and perhaps should be used consistently.

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!');

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('Enter your name: ','');

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 ?');

Example: Interactive 'Hello World!'

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=window.prompt('Please enter your name: ','');
document.write('hello '+name+ ' !');

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. 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.

Examples: Last Update and Current Date

This 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);

The next example introduces the system object called Date. A copy of the object called todaysDate is created using the new operator and then printed.

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

Date/Time Selected Content

Page content can be modified based on the contents of the Date object. An example would be providing a holiday greeting or graphic. Note that getMonth counts start from 0!

<script type="text/javascript">
now=new Date();
if(now.getDate==25 && now.getMonth==(12-1)){
  document.writeln("Merry Xmas everyone!");}

JR's HomePage | Comments [jstutor1.htm:2012 08 17]