Kaye and Geoff's web page documentation 

Introduction

It is well beyond the scope of these pages (and our ability) to teach a complete Javascript course - the book we use for instruction and reference is just under 800 pages! So here we have just provided an introduction to the sort of things that Javascript is used for, with a few simple examples.

Javascript is a block-structured computer language designed to be embedded in and thereby to extend HTML. Note that Java and Javascript are separate languages, no more closely related to each other than they are to other programing languages. Javascript was first created by Netscape, and later added into Internet Explorer, and now is included in all browsers. Inevitably, the implementations of the language are a bit different in each browser, although there is an internationally accepted standard (actually a series of standards) to which all browsers should conform. Although the newer versions of browsers may be moving closer to standards, old versions often treated them as largely irrelevant. In addition, the standard is regularly changed to incorporate new features, so there will always be a large number of browsers which cannot handle the most recent versions of Javascript. Conservative Javascript programmers will, for this reason, always avoid using the most recently-added or non-standard versions of the language.

Javascript is a scripting language, fully incorporated into HTML web pages, with access to HTML elements. It is interpreted by the client's browser and cannot read or write files on the client's hard drive (with the exception of cookies - a special case) - it can only manipulate information on the web page. So pages containing Javascript are not a security hazard, but all browsers allow Javascript support to be turned on or off from within the browser. In fact the latest version of Javascript (version five) does allow limited access to the local disk, but we think that not many web sites have yet used this feature and so we are not sure if it will result in any problems (see the comment at the end of the previous paragraph).

Scripts are typically written to allow the web page to respond to events. Moving the mouse over an image or link, clicking the mouse, loading the page, pressing a key - all these events can be used to trigger a call to Javascript code which typically causes the page to change in some way. And Javascript can control windows and frames which contain web pages, put up alert boxes, control forms, replace pictures and even write HTML 'on-the-fly'.

Mouseovers

The most common effect achieved by Javascript is to have a picture change on the screen when you move the mouse over it - this effect is called a mouseover or rollover, and is relatively simple to include in your HTML. Simple mouseovers can be coded in-line, as part of an HTML tag, using the Javascript code like an attribute of the tag. Here is an example of what can be done with mouseover and mouseout: the magic-wand mouse!

Here is the HTML/Javascript which does it:

<img name="flower1" src="images/rose2.gif" border="0" onMouseover="flower1.src='images/rose1.gif'" onMouseout="flower1.src='images/rose2.gif'">

Note that the original rose image is displayed with a standard <img> tag:

<img name="flower" src="rose2.gif" border="0">
. . . but it has had Javascript actions added to it, causing the image to be replaced whenever the mouse is moved on or off the picture. The two different images used to achieve this effect must be exactly the same size (in pixels).

The same technique can be used to allow mouseovers on one object to change an image on a different part of the screen. This can be a space-saving way of allowing people looking at your web page to control the images they see - for example in a pictorial or a technical presentation where multiple diagrams or graphs are used.... or for something a bit more lighthearted:

The Javascript for the magician effect is very similar to that in the first example, except that there are two pictures and the mouse movement is triggering actions in both these images rather than just one. In the HTML/Javascript (below) which defines this magical mousey behaviour, note the critical role of the "name" attribute - it identifies an image (or other HTML element) and can then be used to specify which image an action applies to.

<img name="magician" src="images/magician1.gif" border="0" onMouseover="flower2.src='images/rose1.gif';magician.src='images/magician2.gif'" onMouseout="flower2.src='images/rose2.gif';magician.src='images/magician1.gif'"> <img name="flower2" src="images/rose2.gif" border="0">

The effects shown here, and the method used to achieve them, are used in most pages where the buttons or other images change in some way as you move the mouse over them, indicating which one is currently selected. However, you should avoid the temptation to take the code snippets shown above and use them without understanding the basic concepts of Javascript; in practice additional code is normally required where you have, for example, a series of buttons comprising a menu. This extra code preloads the pictures so that the mouseover has an immediate effect; otherwise there will be a delay while the alternate picture is loaded.

Complex Scripts

Javascript can be used to do much more than just mouseovers (and there can be more to mouseovers than shown in the example above). For example, you can detect the browser type and version and customise sections of the code to avoid incompatabilities, animated pages can be controlled by scripts, forms can be processed, new windows can be launched, data can be analysed and information written back to the screen. These actions require more than the simple inclusion of a line of Javascript in an <img> tag - you will have to learn the entire language to master them all. In web pages with more complex Javascript, most of the code is usually placed between <script>...</script> tags and typically located in the "head" section of the page, or in a separate file which the browser loads as part of the page rendering process.

If you want to include Javascript code in your pages, you need to be aware that the syntax rules covering Javascript are much more strict than for HTML - typically the use of upper and lower case, and the particular placement of spaces, quote characters and line terminators matters.

In fact, for those without a programming background serious Javascript can be a real challenge, which should not be taken on lightly. If you are in this position, consider taking some sort of formal instruction in the language, or if that is not possible, lessons in another related language (for example Pascal). An alternative may be to find lessons on the web (we have included links to some below), but these often do not take the time to explain the underlying concepts, without which the language may seem to be just an arbitary collection of rules, with little logical context.

Writing HTML on the fly - email address hiding

Estimates suggest that something like three-quarters of email is spam, so anything that we can do to reduce this figure is a Good Idea. Spammers typically harvest email address from web pages by creating 'spiders' - programs which follow links on the web, reading the HTML for each page as they go, looking for "mailto:" or some other indication that the HTML includes an email address. If we use Javascript to write the HTML that specifies the mailto link, then the spiders will only see the Javascript code, and are unlikely to be sophisticated enough to decode it to extract the email address.

Here is an - if you move your mouse over it your browser should indicate that it will send email to info@xxx.com, but there is no HTML associated with this link containing "mailto", or, for that matter, "info@xxx.com". Instead there is a small Javascript function and a line of Javascript code which builds the HTML for the link and presents it to the HTML parser to be rendered as part of the page. The code looks like this:

<script type="text/javascript"> // function hideEmail (e1, e2, e3) { var s1 = '\x6d' + '\x61' + '\x69' + '\x6c' + '\x74' + '\x6f' + '\x3a' ; var s2 = e1 + '\x40' + e2; if (e3 == '0') e3 = s2; var s3 = '<a href="' + s1 + s2 + '">' + e3 + '</a>'; return s3; } document.write (hideEmail('info', 'xxx.com', 'email link')); </script>
The function (called hideEmail) is passed three parameters: the part of the email address before the "@", the domain information after the "@", and the text which is to be presented as the link (in this case "email link"). Variables s1 and s2 are assigned the string "mailto:" and the email address in a way which "hides" their contents from anything other than a Javascript interpreter. The function returns, and therefore the inbuilt Javascript method "document.write" outputs, the complete HTML for the link. If you wanted to give the email address as the link text, for example: contact me at but did not want to include it in the HTML in case the spider was smart enough to pick it out from the "@" character, then you can pass a zero as the third parameter to function hideEmail.

Writing HTML "on-the-fly" is a very powerful feature of Javascript. It allows multiple versions of a page to be created within a single page with the particular version shown being dependent on the browser type, information passed in the URL, or some other characteristic. In theory the entire page could be created this way, although in practice it might be easier to just have multiple regular pages.

Forms validation

It is common for web pages to include a form which allows people to enter information to be sent to the owner of the page. In many cases this information is useless if all the fields are not filled in, or if the data are invalid. For example, a form used to order goods which are to be posted to the purchaser must include their address. Rather than waste time and bandwidth sending incomplete form contents back to the server, Javascript can be used to check that required fields are filled in and that field contents conform to a required pattern, for example that they are numeric, or contain a certain number of characters. The form contents are only sent to the server if the Javascript validation tests are satisfied. Here is a simple example, except that the form contents are not sent anywhere. It assumes that we want an Australian postcode, which are always comprised of four digits:

Enter your post code:
Here is the HTML for the form (without the table elements used to format it):

<form action="#" onSubmit="checkForm(this);return false;"> Enter your post code: <input name="pc" type="text" size="5"> <input type="submit" value="Submit the form for validation"> </form>
and here is the Javascript:
<script type="text/javascript"> // function isfourdigits (s) { if (s.length != 4) return false; for (var i=0; i<4; i++) { if (s.charAt (i) < '0' || s.charAt (i) > '9') return false; } return true; } // function checkForm (exform) { if (isfourdigits (exform.pc.value)) alert ('OK. Your postcode has 4 digits'); else alert ('The postcode must be 4 digits'); } </script>
The HTML for the form is straightforward except for a couple of unusual features - no "action" is specified (it is not required in this case) and the form has an "onSubmit" attribute. This invokes the Javascript code which carries out the validation and also ensures (by returning 'false') that the browser does not attempt to actually submit the form anywhere.

The Javascript (within <script>...</script> tags) comprises two functions; the first returns true only if the characters it is passed (in the variable called 's') are four in number, and all are digits, and the second uses this function to test the form field called 'pc' and display an alert box depending on the result. Of course this test is not strictly for a valid postcode; there might be some four-digit numbers which are not valid postcodes, but it serves to eliminate obviously invalid entries.

It should be clear even from this small example that Javascript is much less straightforward than HTML. We would not try to tell anyone not to have a go at Javascript coding, but to succeed you will normally have to put in some effort, and it certainly helps to start with a good understanding of HTML.

Animation

As you can see from the "magic mouse" example above, one of the things that Javascript is good at is replacing one image with another, at the same place on a web page. Do this fast enough, and you have an animated picture. While Javascript can be used to create animations, problems often arise because of the way that the screen refreshing is handled by most browsers. It seems that the updating of an image in Javascript does not trigger an immediate screen update; in fact nothing is changed until the code halts to wait on the next event. The effect is that only the final frame is displayed!

We have spent a lot of time trying to get around this problem, but have not come up with a satisfactory solution. The setTimeout function (it allows you to exit a function while automatically triggering another or the same function to run at a prescribed time in the future) can provide a solution but it usually requires that many variables which you would like to be local must in fact be declared globally, and generally makes a complex mess of carefully constructed code.

If you want to see examples of animation driven by Javascript, and look at the code they use, our site has a variety of different examples, in particular those available from our kids games page. The dragon game, for example, uses straight-forward image replacement to move the pieces turn-by-turn for standard moves, but uses the setTimeout function when a series of actions are required without the player taking a turn.

Time-dependent code

We have all seen web pages with lists of "upcoming events", many of which are now well and truly in the past, or maybe "Merry Christmas to all our customers!" messages which are still on the page in March. Besides being useless information which tends to crowd out the relevant stuff, they give the impression (possibly with some truth) that the web site owners are lazy slobs who cannot be bothered to keep their web pages up to date. However, we web page maintainers lead very busy lives and it can be easy to forget that the friendly message or events we added a month ago have now outlived their usefulness.

Javascript to the rescue! We just need to put a bit of effort into how we display the time-dependent information and then sit back and over-indulge in festive cheer, knowing that the Christmas salutations on our web site will be automatically "removed" even before we crawl out of bed on Boxing Day. How can this be done?

We can take advantage of Javascript's ability to create HTML "on-the-fly" and the fact that it can obtain the current date from the operating system. We need a function, such as the example below, which compares a number which represents a given date to another number which is similarly derived from the current date. The function returns true or false depending on which number is larger (ie. which date is earlier).

function isFutureDate (comp_date) { var today = new Date(); var todays_year = today.getFullYear(); var todays_month = today.getMonth(); var todays_day = today.getDate(); var calc_date = todays_year*10000 + (todays_month+1)*100 + todays_day; if (comp_date > calc_date) return true; else return false; }

We use the result returned by this function to control whether or not we create the HTML to display our message. The code is placed on the page where we want the message to appear, and it might look like the sample below. Up until the end of December 25, 2011, isFutureDate will return true so the page will say "Happy Christmas to all our friends!" but thereafter the function will return false and nothing will be displayed.

<script type="text/javascript"> if (isFutureDate (20111226)) { document.write ('<p>Happy Christmas to all our friends!<br>'); } </script>

Variations on this theme could be used to make a message (or a link, or a picture or whatever) appear in the future, or on a particular day, or for a given period. Notices of annual events can be set up and will then appear and disappear at the correct times indefinitely and with no further interference.

More information about Javascript

We use Javascript, The Definitive Guide by David Flanagan, ISBN 1-56592-392-8 published by O'Reilly, as our Javascript bible (although it is getting a bit out-of-date now).

Top
Previous
Next
Index
Home