Next page | Contents page |

Explaining the date/time code

The HTML insertions

Three changes were made to index.html in the preceding exercise:

  1. A script tag was inserted in the head to cause the JavaScript file, datetime.js, to be loaded:
    
      <script type="text/javascript" src="datetime.js"></script>
    
    The .js file is in the same directory as index.html. We can tell that because there are no slashes in the value of the src attribute, that would indicate a directory path structure. In large systems it would be a good idea to put JavaScript files in a separate directory. If that was called js and was an immediate subdirectory of the one containing index.html then we would instead have written
    
      <script type="text/javascript" src="js/datetime.js"></script>
    

    Forward or backward slash?

    The Internet is not tied to Windows so forward slashes (/) are always used in file paths in HTML and JavaScript, even when working on a Windows machine.

    In other words the value of the src attribute can specify a path to the file, not just its name.
  2. The starting body tag was modified to insert an attribute, so it became
    
      <body onload="showDateTime()">
    
    The value of this onload attribute is in fact a JavaScript statement. It gives the name of a function (to be described soon) and a pair of empty parentheses which mean that we want to invoke the function (execute it as a piece of program) from here.
    So this is a third way of starting some JavaScript running: a statement (probably invoking a function) as the value of an event attribute.
    The name of the attribute, onload, means perform the action only when the browser has finished loading the whole page (the HTML file, the JavaScript file, and anything else that may have been specified, such as images). It is important not to try to run a program before it is known to have been loaded.
    onload is the first example we have encountered of what is known in JavaScript as an "event". Other examples of events are when the user clicks a mouse button or presses a key on the keyboard. We will see later how a program can respond to such events.
  3. A MOTW line was put at the start of index.html to ensure that it would work in Internet Explorer without irritating warnings:
    
    <!-- saved from url=(0014)about:internet -->
    
    The symbols <!-- and --> mark the start and end of a comment in HTML, that you might use to explain (for future maintainers) why you did something a particular way. Comments do get loaded by the browsers but are not displayed as part of the page. End users can see them via a "View source" menu option, so be careful not to give away anything that should be kept secret.

The JavaScript code

Now we get to the nitty gritty: the program in file datetime.js which looked like this:


function showDateTime ()
{
  var now = new Date ();
  document.write ("It is now " + now);
}

The words function and var are examples of "keywords" in JavaScript: words that are reserved for a particular purpose and may not be used in any other way. There are a few tens of reserved words and we will encounter several of them in this course.

Identifiers

You are free to use any name for a function or a variable as long as it is not a reserved word, that it starts with a letter and ends with any combination of letters and digits. You will make life much easier for yourself if you use meaningful names rather than abbreviations.

Identifiers must not contain spaces or other punctuation (except underscores, _). A common practice is to run words together, using a capital letter for the start of each word (except the first - explained later). This is known as "camel case" because it has humps! In our code here showDateTime is an example.

A function is a self-enclosed chunk of program that can be executed from anywhere else by giving its name followed by the parentheses, as we saw in the onload attribute. For some functions the parentheses may contain a comma-separated list of values called parameters. Parameters will be discussed further when some are needed.

A function has a body that is enclosed in curly braces, as in the example. The body contains the statements that are executed in sequence when the function is invoked. There may be one or more statements beginning with keyword "return", to return a value to the code that invoked the function, but again we will describe those when we need them. They are not needed here because the result of the function is to modify the displayed page.


  var now = new Date ();

The keyword var announces that we are defining a "variable". That means a location in memory for holding some data. We give such locations names so they can be referred to again later. So here our name for this variable is "now". In this example we are also putting something into the location: data defining the current date and time as obtained from the system clock. The code new Date () has that effect. (Strictly it constructs an object of type Date, but that is getting ahead of ourselves for now.)

Finally the statement declaring the variable and assigning a value to it ends with a semicolon. Now in JavaScript it is not essential to end every statement with a semicolon. A new line would suffice. However, if you go on to write large programs you will find it helpful to use semicolons and therefore it is good to get into the habit now.

DOM

When we use JavaScript in HTML, as we are doing in this course, the browser displaying a page automatically constructs a data structure called the DOM (Document Object Model) in which every feature on the page is represented in some way. JavaScript enables us to access all parts of the DOM and manipulate it so the page changes. A most important object in the DOM is of course the one called document, to which just about everything in the page is attached. The document is a specific data type (in fact Document, with a capital D) that always has a certain set of functions available for us to use. And write() is one of those functions. We will meet another one very soon.

The second statement inside the function is quite different:


  document.write ("It is now " + now);

This statement is invoking a function called write() that is part of a variable called document. The dot between document and write tells us that write() is part of document. And document.write() is a function that requires one input parameter, of a type called String. That is, a string of text characters.

The String parameter we are passing into write() is built from two parts, concatenated together by means of a plus sign (+). The first part is plain text enclosed in double quotes ("). The second is a string representation of the data held in our variable called now. The conversion to a string happens automatically because the literal string ("It is now ") and the concatenation sign make it unambiguous that that is what is required.

The effect of invoking document.write(), the way we are doing it here, is to replace the contents of the entire document by the String we are passing to the function.

By the way

The standard for JavaScript is owned and maintained by Ecma International (originally the European Computer Manufacturers Association). The standard calls the language ECMAScript, which does not exactly roll off the tongue and so has not caught on. ECMAScript and JavaScript are synonyms and may be used interchangeably.

The full standard (Ecma-262) may be downloaded as a PDF file from Ecma's site here. That covers the core language but not the objects comprising the DOM, or their functions.

The DOM is a World Wide Web Consortium standard and all the formal documentation can be found on the W3C site here.

Keep those highly detailed formal references for later, don't try to run before you can walk! Carry on with this course first. These reference links will be collected together in a page at the end of the course.

Next page | Contents page |