Previous page
BACK

Part 7 - The end, and beginning
(Events, a summary, and further reading!)

 
Contents
  1. All your Questions Answered
  2. More Event Handling
  3. Netscape Events
  4. MSIE Events
  5. Common Ground
  6. Fine Print
  7. Further Reading
  8. Back to Page One

All your questions..

A quick list of demonstrations

Here are most of the demonstration JavaScripts on our tutorial pages:

What have we learnt so far?

  • We've learnt what JavaScript is, and acquired a blurry idea as to what a scripting language really is (opionions seem to vary a bit)!
  • We've found out how to hide JavaScript from naïve browsers, and how to write a very simple script.
  • We can identify different browsers.
  • We've found out basic ideas about functions and strings.
  • We can create variables and comments. (We explored this in more detail later).
  • We understand the if statement - at least, one simple, consistent variant of it! (We also discovered a quick, dirty trick to select between two choices).
  • We can do repetitive actions using while (which we encountered in part two). In part six we found out about similar constructs - for, do, break, continue, with, switch, and possibly the most useful of the lot: for .. in.
  • The Boolean values true and false present no problems to us.
  • We know about the overall structure of object-oriented programming, including methods and properties, and also some details of its philosophy (including encapsulation, polymorphism and inheritance).
  • Early on we met the methods indexOf, parseInt, and toLowerCase.
  • We learnt how to make an extremely simple, rather useless form, and later on how to create a detailed fully-interactive form. We also explored the form object.
  • In addition on the second page of our tutorial, we explored a quick and dirty method of passing information between pages (without using frames), and we found out how to concatenate strings.
  • We found out that JavaScript shares a lot in common with Java and indeed with C and C++. We looked at arithmetic in some detail. Because JavaScript uses mainly infix notation, there are complex hierarchies that govern function precedence. This sounds intimidating, but you encountered it in a slightly different form in primary school!
  • We know the JavaScript data types - strings, numbers, Booleans, objects and arrays. (Here we also encountered null and the null string ""). We also explored binary logic, and trigonometric and other functions - methods of the Math object.
  • We know that the Top Level Objects in JavaScript are only two - window and navigator. But each of these has multiple methods and properties which differ from browser to browser. The most important property of the window object is the window.document object. This is structured according to a 'Document Object Model' (or DOM) which has only recently been standardised. The document object has multiple properties including the important forms, images and links objects. We found out how to document.open() and also write and close documents, and that you must not confuse this with window.open(), which is used to create new 'pop-up' windows.
  • You understand the pre-defined date and string types.
  • Incidentally, we found a crude and a more elegant way of finding out the JavaScript version.
  • We explored events in detail, including mouse, focus, error and form events.
  • We found out how to write to the window status bar.
  • We learnt that if you capture an event using JavaScript and then return false, the consequences of the event are cancelled.
  • We briefly discussed client-side image maps.
  • We know a little bit about intercepting events in JavaScript 1.2 - the details have been left to later on in this page!
  • We learnt a lot about frames, including a fun demonstration [which incidentally taught us a bit about things like document.write() ]. The most important thing we learnt was that a frame has all the properties of a window.
  • We also found out about targets.
  • We have eaten perhaps more cookies than is healthy.
  • We know a bit about layers, how they can be used in animation, and the conflicting layer designs of Netscape and Microsoft.

What this tutorial didn't cover

There are many topics that we haven't covered. These include:
  • Java applets;
  • Plug-ins;
  • CGI scripts (well, not yet);
  • Intranets;
  • VRML and JavaScript;
  • JavaScript style sheets, nor indeed
  • Cascading Style Sheets, for which there is a good reference here;

There's tons of stuff out there on the web that covers all of these topics (admittedly, a lot of it rather disorganised). Go get it!

At present, we're plodding through the W3C DOM levels 0 to 2. When we've assimilated these, we hope to revise this tutorial rather extensively. You may wish to visit the W3C to pick up zipped copies of their recommendations.

Other stuff

A lot of other tricks and smaller things are covered in our fine print section below.

If you have a really burning question that's not covered in our tutorial, and you've done a thorough search on the net without any joy, feel free to ask us. We're not JavaScript boffins, but we'll generally try and help if we can! Here are a few examples:


'Advanced' Event Handling

Unfortunately, Microsoft didn't learn learn much when they diverged from Netscape early on in the creation of 'JScript'. They perpetuated problems by proposing their own methods of event handling. Some of this was to allow their own peculiar internet BASIC to be used as a scripting language. (To be fair to them, in several ways their event handling is perhaps somewhat better than that of Netscape)! We will first outline how Netscape upgraded the event-handling capabilities of JavaScript in version 1.2 (With Navigator 4), and then how Microsoft has diverged.

A. Event handling in Javascript 1.2 (Netscape)

We know that the original method of handling an event was to say something like:

<body onLoad="Dosomething();" >

where the user-defined function Dosomething() is invoked when the web-page body has finished loading. We also know that one can put in several such statements separated by semicolons, and that returning false cancels any further action in for example an anchor. All of this still applies in JavaScript 1.2, but there is a lot more. Note that there are three reasons why you should avoid this new functionality:

  1. It's not backward compatible with older browsers;
  2. You have to account for differences in Navigator and IE;
  3. It can be confusing.

Conversely, the new approach often confers abilities that are sorely lacking in older versions! You have to balance the risks and the benefits.

What is the new approach?

The new approach is simply to say:

        object.eventhandler = function

here, you specify the name of the event-handling function without any following parenthesis. One might for example say:

window.onload = Dosomething;

There is a significant irritating requirement here - despite the event being onLoad, for compatibility with Navigator 3.0, the whole darn thing must be written as onload - that is, all in lower case! The same applies to all event handlers - write the silly things as lowercase (You might look through the preceding six pages and see how often we've erred in this regard. Gosh)!

There's another major catch - it's all very well to dynamically allocate a function to, for example, a button or anchor, but beware - the button (or whatever) must have been defined before you allocate the function to it. For example, if you say

document.forms[0].button[0].onclick = fred;

in JavaScript in the head of a document, this will fail as silly old JavaScript will try and run the code before it's created the button. A solution is obvious - only run the allocation when the body of the document has loaded, using onLoad.

Capturing Events using captureEvents

The method captureEvents() adds further power. In version 1.2, this method, as well as releaseEvents() are defined for windows, layers and documents. They allow you to intercept events before they get to their destination! You can specify a variety of events that can be captured, for example:

  • Event.CLICK
  • Event.MOUSEDOWN
  • Event.MOUSEUP

Note that here, for reasons best known to Netscape, the events are spelled in UPPERCASE! Every event to be captured must be preceded by Event. An added frill is that multiple events can be specified, thus:

window.captureEvents(Event.CLICK | Event.MOUSEDOWN)

and so on.. Separate the events with | pipes |

You don't have to release all the events you are capturing at the same time. You might for example say the above, and then later:

window.releaseEvents(Event.CLICK)

leaving Event.MOUSEDOWN to carry being captured!

Once you've specified the event to capture, you still have to specify a function that does the actual capture! This is a major clumsiness, but all you do is you use the now-familiar new approach, for example:

window.onclick = whatever;

Event Capture in detail

Once one has captured an event, how does the event handling function deal with it? We've already covered this in part four of our tutorial, but to recap:

JavaScript passes an event to the function. In JavaScript 1.2, every event is also an object! We say for example:

        function Dosomething (ev) { /* function definition goes here */ }

and then can talk within the function about the properties of the event ev passed to it. As expected, we can return false from a event-handling function to prevent further processing, or true to allow normal handling to continue.

Note that you can also talk about an event object from within a tag, for example you could say:

<a href="whatever.htm" onClick="alert('Hi you did a ' + event.type)" >

where the special object reference event allows you to refer to the properties of the click event. (We will later describe all the properties associated with all the events in JavaScript 1.2)

The handleEvent() method

This is a cute wrinkle - you can use it to force a particular object to handle an event. For example, in the above our handler Dosomething might pass control to a particular link thus:

document.links[0].handleEvent(ev);

.. where we have previously set up an event handler for the link referred to!

NOTE that if you refer an event to another handler, that handler cannot directly cancel the event. Only the first recipient of an event can cancel it! However, this is easily sorted out - you can pass information back up the chain to the original recipient. Say:

outcome = document.links[0].handleEvent(ev);

within the first handler, and then return the value of outcome from the first handler, to either cancel or not cancel the event!

handleEvent cannot be used in layers.

routeEvent()

[look this up]

All the events

Here is a list of events for JavaScript 1.2 (Navigator):

All the events for 1.2
Event Meaning Discussed below in..
keydown key is depressed Section 1
keypress key press (including repeats)
keyup key release
click click on an item (Note that in Navigator, but not IE, the Backspace key generates a click event!)
dblclick doubleclick (avoid this)
mousedown mouse button is depressed
mousemove mouse is moved
mouseup mouse button is released
mouseover mouse cursor moved over something
mouseout mouse cursor leaves something (was over)
dragdrop a system file (or other item) is dragged and dropped onto a window
blur item loses focus for key input Section 2
focus item gains focus
change contents of a box change
error a loading/JavaScript error occurs Section 3
load an image or document finishes loading Section 4
unload an image or document is killed
move a window is moved Section 5
resize a window or frame is resized

We will examine the lot in the following sections.

1. Keypress and Mouse Events

These events can only be trapped in JavaScript 1.2; NOT in earlier versions.

Trapping a keypress

When a key is pressed, there are 3 events generated. The corresponding handlers, in order, are:
  1. onKeyDown
  2. onKeyPress
  3. onKeyUp
They are all similar. We'll use onKeyDown as a prototype:
onKeyDown
This applies to: document, Image, Link, Text and Textarea objects

Javascript passes the event handler an object with the properties:

  • target = the original object target
  • type = "keydown" (always)
  • layerX = horizontal pixel position of mouse in layer at time of event
  • layerY = similar, but Y position
  • pageX, pageY = similar, but in relation to the document
  • screenX, screenY = also similar, but in relation to screen!
  • which = the ASCII value of the key pressed
  • modifiers = bit image of modifying keys pressed at the same time (Shift, Ctrl, Alt, and Meta).

To cancel the key event, the event handler should return false. One could for example "re-route" typed input from a text box to elsewhere by capturing the keypress event and then using it elsewhere.

The modifiers
How do we check the modifiers to see which key was pressed? We perform a logical AND between the number contained in the modifiers, and a mask value. In other words, a single bit is set for each of the keys, and we mask out all the other bits, leaving a value of zero if the flag isn't set, or non-zero if it is. The possible mask values we can use are:
  1. Event.ALT_MASK
  2. Event.CONTROL_MASK
  3. Event.SHIFT_MASK
  4. Event.META_MASK

We might say something like:

      if (ev.modifiers & Event.ALT_MASK)
            { /* do something */ };

which would do something if the Alt key was depressed when the event occurred.


 

onKeyPress and onKeyUp
These are similar to onKeyDown. Holding a key down for some time (how long?) will result in repeated keypress events, which you can intercept. You could also for example record the time when a key is released by recording the Date() in a handler for onKeyUp.

Trapping a click on an item

We have already provided an example in
part four. Here we flesh things out.
onClick

This event occurs with document, Button, Checkbox, Link, Radio, Reset and Submit objects. The onClick event can be detected in JavaScript 1.0, but the event handler only works in 1.2 and above. The event object passed to the handler has the following properties:

  • target, layerX, layerY, pageX, pageY, screenX, screenY and modifiers are as for a key event;
  • type = "click" (always)
  • which = 1 for a left mouse click, 3 for a right click;

Note that if you click on a button, the coordinates returned are (0,0). As usual, if the handler returns false, then the action invoked by the click is cancelled.

Mouse Clicks: onMouseDown, -Move, -Over, -Out and onMouseUp
These events are only captured in JavaScript 1.2 and above. They are very similar to the click event described above. Note that the onMouseDown and onMouseUp events precede the onClick event! If the onMouseDown event is cancelled (returns false) then NO click event will be generated. There is also an onDblClick event and an onDragDrop, the meanings of which are obvious.

onDblClick works with Button, Checkbox, document, FileUpload, Link, Password, Radio, Reset, Select, and Submit objects. It doesn't work on Macs!

onDragDrop is a specific event associated with windows, invoked by ondragdrop, self.ondragdrop, or window.ondragdrop (Hooray for redundancy). It's used to drag a file onto a window - the browser's default is to load the file (except with FTP). Note that dragdrop implies that the system's drag and drop mechanism has been invoked - the thing dragged and dropped onto the navigator window is a system item. You can also use windowname.ondragdrop, where windowname is the name of the window object. The object associated with onDragDrop has the properties type (unsurprisingly, equal to "dragdrop"), target, and data. The data property is an array of strings containing the URLs of the dropped objects! There are lots of security constraints governing whether you can actually read the .data property! (You need a signed script with 'UniversalBrowserRead' privileges).

If one traps the onMouseDown event, then one can override the normal response to a right click and turn off the pop-up menu that usually results. The type attribute of the object provided for all of these reflects what event was trapped e.g. "mousemove".

Note that by default mouse movements are not passed to objects. You have to first specify:

        captureEvents()

We already know that objects that can invoke captureEvents() are windows, documents and Layers. Take care - a vast number of events will be generated by a single mouse movement. An example of a layer tracking a mouse movement is:

Moving a frame with the mouse (Netscape 4.x)
(from databynet.com)
function trackMouse(ev)
 { myLayer.pageX = ev.pageX
 myLayer.pageY = ev.pageY
 }

 document.captureEvents(Event.MOUSEMOVE)
 document.onmousemove = trackMouse

2. onBlur, onFocus and onChange

onBlur initially only applied to Select, Text and TextArea objects. In version 1.1 Button, Checkbox, FileUpload, Frame, Password, Radio, Reset and Submit objects acquired it, and in 1.2 layers were afflicted with it. Likewise for onFocus. Beware with using onBlur and onFocus with alert boxes.

onChange is rather boring, applying to Select, Text, TextArea and FileUpload objects, the last only being introduced in version 1.1.

3. onError

Only introduced in version 1.1, this applies to Frames, Images and windows. For images, this means a problem with the image file; for frames and windows, a JavaScript syntax or run-time error must have occurred. Note the rather unusual format of the information passed to the handler if the problem was with a Frame or window - three arguments are passed:
  1. A string describing the error;
  2. a string = the URL of the document;
  3. a number = the line number where the error occurred, unless the document has finished loading, where the number is unreliable, only indicating the last line of the document.

You can suppress JavaScript error messages by setting onError to null, thus:

window.onerror = null

4. onLoad and onUnload

You already know how useful onLoad is - we've used it often in the preceding pages. It works for Frames, Images, Layers and windows. The handler is passed a boring object with just two properties - target and type.

Note that if a frame has multiple children and both parent and children have onload handlers, the children get a slice of the action before the parent does. Each time you modify an image's src attribute, a load event occurs once the new image has loaded. Even more interesting are animated GIFs - every time the picture changes, a load event is generated! (If these changes occur frequently, you can crash your JavaScript)! onLoad is NOT called for a new Image() constructor.

The onLoad handler for images was first provided in version 1.1.

Note how with HTML one can say:

<BODY ONLOAD="confirmEntry(event)">

to pass the associated event to the function confirmEntry. This is a general paradigm that can be used with a lot of event handlers, ie using event within the tag.

onUnload is similar - applying only to windows. It may be used in frames, but is never called!!

5. onMove, onResize

Says whether a window or frame has moved - only from version 1.2 up. The event object contains:
  • type="move";
  • target, as usual;
  • screenX and screenY, the coordinates of the mouse pointer at the time of the move event.

You may wish to use onMove with window properties such as outerWidth and outerHeight; as well as screen.Width and screen.Height ; Something like:

will also work!

onResize also applies to windows and frames. The event object is very similar to that of onMove, but contains width and height rather than screenX and Y.

Why Netscape's model is peculiar

Think about it - you can either trap an event at the object where it is directed (for example, when you click on a button), or you can intercept all clicks on the document! Now what happens if you have used captureEvents() to set things up to intercept all clicks, a click occurs, and no handler exists to process it? Well, Netscape has set things up so that if an event is not captured by the document that contains an item, the click will "filter down" to sub-components of the document, and eventually (if not trapped along the way) it will reach the component that was clicked on.

Once however a handler has grabbed hold of an event, that's it (unless the handler explicitly passes the event on to another element).

When we examine Microsoft's approach, we'll see that it's completely the opposite! With MSIE, events "bubble up" from the component lowest down in the hierarchy to progressively broader document elements. All of this occurs automatically, and you have to specifically prevent events from bubbling up to higher levels.


B. Microsoft Event Handling

In IE, every element on a page is an object, and has events associated with it. Much of the event-handling you have learnt with Netscape also applies to IE. The object.eventhandler = function approach works here too. But there are several differences.

With IE, you can also put a lot more detail into the <SCRIPT> tag - specifically you can put in EVENT="onclick" (for example) and FOR="document" (say) - this will allow you to trap and handle document onclick events. Using this wrinkle is generally pretty pointless, as there are usually other ways of doing the same thing, and it won't work with non-IE browsers. You should still be aware of this as you might encounter it in other people's scripts! Note that there are lots of Microsoft rules governing where you can put such scripts - basically, if you are using this approach to write an event handler for a form element, you must have the code within the FORM, unless the form element has a unique name.

Most important about IE events is that there is no explicit method by which a window or document can capture events - the captureEvents() method is simply not defined! This is not necessarily a bad thing as all you need to do is specify say document.onclick = whatever; in the usual way to get the document to capture (say) all click events.

Event Bubbling

Consider the case where a document component is contained within another component, for example, an area of italic text is contained within a paragraph. In IE you can associate each of these components (the paragraph and the italic text) with its own event handler. Now, when you click on the italic text, who gets the click? The short answer is that the lowest element in the hierarchy gets the event first, and the event then 'bubbles up' to the next level, and so on. Contrast this with the way Netscape uses captureEvents() to grab the event at the highest possible level!

The event object

Both Netscape and IE have an event object, but there are substantial differences. The most important one is that you can only refer to event in IE during an event - that is, when you are inside an event handler handling an event! (You don't have to say window.event, you can simply say event). You do NOT (as we did with Netscape) specify the event as an argument for the event handler - it's just magically there when you need it!

What are the properties of event?

These are very similar to those of the Netscape event that is passed to an event handler. The difference is that in IE, every event has the same set of properties (just some don't have any meaning, heh). Here they are:

MSIE 4 event properties
Event property What it contains
srcElement who initiated event. The same as Netscape's target
type a string, just as in Netscape
clientX, clientY mouse co-ordinates at the time of the event, of the mouse with respect to the page of the target object (in pixels). Similar to Navigator pageX, pageY, but clientX and clientY don't take scrolling into account. Thus:
pageX = clientX + document.body.scrollLeft;
pageY = clientY + document.body.scrollTop;
screenX, screenY Similar, but coordinates relative to screen. Identical to Navigator ScreenX, ScreenY
offsetX, offsetY Similar, but coordinates relative to container element (read-only)
x, y mouse coordinates relative to an element in the parent hierarchy of the object. The element must have been positioned using the CSS positioning attribute!
button The mouse button pressed but right clicking will only display a little context-sensitive menu on most Microsoft-based systems! Pretty useless. The primary button has a value of zero, but this is also the value returned by the middle button on some systems. Trust nothing and nobody!
Netscape uses which (see also keycode)
keycode The UNICODE key code for the keyboard key that was depressed. To all intents & purposes, the ASCII code is the same on most systems. Only with key events, and note that this value can be overwritten! Netscape uses which for this too.
altKey, ctrlKey, shiftKey Says whether these were depressed when the event occurred. They are Boolean - true when depressed. These are equivalent to the Netscape modifiers attribute. Note that the ctrlKey property does NOT work on the Macintosh version of IE 4. IE 4 does NOT support the Meta modifier key.
cancelBubble Discussed below - set it true to cancel propagation of events (bubbling).
returnValue Setting this false is the same as returning a value of false. (With consequences as for Netscape).
reason You'll rarely use this - it says (with data transfer from a data source) whether data transfer succeeded (0), was aborted (1) or failed (2)
srcFilter This only fires with the filterchange event, and tells us which filter object caused it to fire. [We haven't discussed filters]
fromElement, toElement Gives references to the elements the mouse is moving from, and to.

Microsoft has introduced a vast number of events that can be trapped. Some of them might seem strangely familiar to you:

  • keydown, keypress, keyup
  • mousedown, mousemove, mouseover, mouseout, mouseup
  • click, dblclick

Note that in IE, any element can fire-off a mouse or keyboard event, which is quite different from (and more powerful than) Netscape. We don't know what the overheads of such an approach are.

For a doubleclick, the sequence of mouse events click is (from first to last):

  1. mousedown
  2. mouseup
  3. click
  4. mouseup
  5. dblclick

Clicking with the mouse is not the only way to generate a click event - pressing enter on an element that can receive the focus will also generate a click!

Cancelling event bubbling

This is easily done. Set the cancelBubble property of the event object to true, thus:

        window.event.cancelBubble = true;

and that's it! Note that this cancels bubbling only for the specific event being processed at the time. Another important point - if you return false from an event handler, then event bubbling will also be cancelled for that event, but the default action associated with the event will not occur - just as you would expect from the Netscape behaviour.


Cross-browser Events

There are many differences between Netscape and IE. It's best to write your code to support both, so avoid functionality that isn't present in both. Practically this means:
  1. Don't attach onClick (or other mouse events) to any of the wealth of options allowed by IE. Stick to:

    <A >   <AREA >   button   <IMG >   and document.

  2. If you use captureEvents(), then check that the browser supports this. The way to do this is simply to test:

    if (window.Event) { /* here captureEvents is ok */ };

    The condition will only succeed with Netscape or compatible browsers that support captureEvents. Note that within an event handling routine IE will identify something called window.event, but it will still not possess window.Event, which is peculiar to Netscape! So you can always tell the difference!

  3. You can similarly use "if (window.Event)" to set up a global variable that tells your event handlers how to handle events. If you're in Navigator, then you'll clearly use the event passed to the routine; if in IE, window.event.

Fine Print

You can deduce the answers to many of your questions about JavaScript by simply reading our tutorial (all of it) and thinking a bit. For those other niggling questions, you might browse the following..
  • Okay how do I write to a file from JavaScript? You can't, and that's it! We think this is a major defect in JavaScript, despite its "security benefits". To read a file from a friendly server, using a Java applet, see this link! Apparently MSIE 4 can read text files using 'data binding'.

  • Can I encrypt my scripts so nobody can read them? Microsoft is apparently working on this. We hate the idea.

  • How does security work? This is beyond the scope of the tutorial (at present). Later on we hope to write a whole tutorial on security issues.

  • How do I highlight all the text in a box, using JavaScript? Try this (after defining a text box called fred):
    <input type=button value="Highlight All"
     onClick="javascript:this.form.fred.focus();this.form.fred.select();">
    

  • Can I write layers dynamically? Absolutely. You can obtain magnificent effects. Check out the demonstrations at foxglove. Make sure you don't exceed the limitations of common browsers (i.e. MSIE 4)!

  • I heard that I can use REGEX (regular expressions) in Netscape. Is this true? You can, from 4.0 . Methods involved include compile and exec, and look out for properties that a Perl user would expect, such as $1..$9, $_, $* and so on. Regex is part of the Ecma standard.

  • You haven't put in enough about making new objects. Why not? True. This page is far from complete. (Would you like to add something?)

  • How do dynamic fonts work? Hmm. Another thing we didn't cover. At present they strike us as a bit tricky, but doubtless this will change. Check them out on the internet.

  • How do we test if something is an object? (as opposed to e.g. a string?) If you want to test if fred is an object, say something along the lines of:
      var testvar = "" + fred;  //coerce to a string
      var isobj = (testvar.indexOf("[object") > -1 ); //true if IS an object
    

    Not a guarantee, but a pretty good guess!

  • How do I change styles of objects in MSIE?Try:

    <SCRIPT LANGUAGE="JavaScript">
    function setHeadStyle() { window.event.srcElement.style.color = "green";}
    
    document.all.MyHeading.onclick="setHeadStyle()";</SCRIPT>
    

  • What was that quick & dirty thing with the question mark and colon that allowed us to allocate one of two choices? Here it is again:
             fred = ( ( jane == 1) ? "yes" : "no" );
    

  • How do I refer to a frame that's a component of another frame? [Think about it - a window and frame have the same properties].

  • How do I set up a single event to occur after a certain delay? Use setTimeout(routinename, milliseconds). Note that the routinename must be encased in "quotes" and followed by () Clear the timeout before its execution using clearTimeout, which is similar to clearInterval (below).

  • How do I set up a repeating event? Use setInterval(routinename, milliseconds). For an example, see the source for our playing with windows. Similar to setTimeout. You clear the repetitive event using clearInterval(handle), where handle is the handle returned by setInterval.

  • Can you send email from a form? Internet Explorer doesn't support mailto: within forms. Netscape does. Check out the web, for example irt.org, which gives you:
    Set the Mail To: using: <a href="mailto:?to=someone@somewhere.com"></a>
    Set the Cc: using: <a href="mailto:?cc=someone@somewhere.com"></a>
    Set the Blind Cc: using: <<a href="mailto:?bcc=someone@somewhere.com"></a>
    Set the Newsgroups: using:<a href="mailto:?newsgroups=comp.JavaScript.lang"></a> 
    

  • Am I in a frame?Try:
    <body onLoad="if (parent.location.href != self.location.href)
         {... do something ...}; return true;">
    

  • Can I beep? Only in Netscape! Try:
    <SCRIPT LANGUAGE="JavaScript"><!--
     if ((navigator.javaEnabled != null) && (navigator.javaEnabled()))
        { java.awt.Toolkit.getDefaultToolkit().beep();
        };
    //--></SCRIPT>
    

  • When did arrays appear in Netscape Navigator? Version 2 (but only as an object in version 3, together with Blur, Booleans, focus, functions, taint, untaint and so on).

  • What about disableExternalCapture, enableExternalCapture? Also getSelection, and layer.load, string.match, date.parse (?) array.push, navigator.plugins.refresh, string.replace, array.reverse, array.slice, string.slice, window.stop, object.unwatch; also array.index, array.input [Hmm]

  • How can I highlight text with the mouse?See irt.org FAQ #120.

  • How do I play a sound? Use EMBED in Netscape - try:
    <EMBED SRC="sound.wav" HIDDEN=TRUE>
    

    IRT.ORG faq #191 gives more details, including how to do this with MSIE.

  • Can you cache sounds? Yes, thus (from irt.org):
    <EMBED SRC="sound.mid" HIDDEN="TRUE" AUTOSTART="FALSE">
    

  • Can I change the mouse cursor? In MSIE, yes. Not in Netscape (as far as we are aware). Use:
    document.all("itemname").style.cursor = 'hand';
    

    .. or whatever. Styles available are: auto | crosshair | default | hand | move | e-resize | ne-resize | nw-resize | n-resize | se-resize | sw-resize | s-resize | w-resize | text | wait | help

  • Can I print the contents of a frame by clicking say a button in another frame? Not in IE4. Yes for Navigator 4, or IE 5, thus:
     <INPUT TYPE="button" onClick="if (window.print) top.framename.print()">
    

    Printing a window is identical: windowname.print(); irt.org has vbscript that will allegedly do the same for IE4. (FAQ #481).

  • [Perhaps we should have something on detecting NN 4.06, which freezes if style text decoration=none set in tag]

  • How to specify unicode characters? Use "\uNNNN" where NNNN is the unicode character. Note also the problems one sometimes encounters with accented characters. NB NN4 is not fully unicode-compliant (I4 is).

  • How can one bookmark a frame? See irt.org FAQ #174.

  • Are browsers Y2K compliant? Not IE3 or NN2. Others should be.

  • Can I alter text within the cells of a table? In MSIE 4, not Navigator 4. Use document.all("tdIdentifier").innerText = something; after you've named the td thus: <td ID="tdIdentifier" > or whatever.

  • Can JavaScript add a favourite? Yes, but only in MSIE. Try:

    <a href="javascript:window.external.AddFavorite('http:/www.irt.org/script/','Javascript FAQ')">Bookmark</a>

  • Where can I get stuff on style sheets? Go on! Here and also here.

  • [We need stuff on the W3C DOM definition - "Document Module Levels"]

Further Reading

  • By far the best introduction to JavaScript that we've found on the web is at irt.org. Feast your eyes - it's short and packed with useful recommendations. The site has a host of other tips.

  • A brilliant source for Netscape stuff is on their site. You can download a reasonably-sized zipped manual for JS 1.3. There's also the NETSCAPE JAVASCRIPT GUIDE, and the NETSCAPE DYNAMIC HTML page. The NETSCAPE V3 GUIDE is dated, but this can be a merit! For NETSCAPE EVENT HANDLING, try here.

  • Here's some more Netscape Event Handler stuff (good).

  • You might want to peek at some of Microsoft's documentation. An explanation of the MSIE DIV TAG is worth a read. If you visit their "official JScript documentation", be prepared for a rude shock. To download their off-line documentation, you will first have to download their HTML help authoring guide, HTML help activeX control reference, and HTML help API reference. (Over a Meg). Then only can you get the JScript documentation! If you then open MSIE and double-click on the jsdoc icon, you are told that something has been extracted (a new file called JS55.CHM appears) but then if you double click on this file and are still running Windows 95, you'll more-likely-than-not be told that Windows cannot find hh.exe. Quickly install Windows 98, and you're away! Where do you want to go today? Hell seems a good option! If you visit the Microsoft online language reference in, say, Netscape Navigator version 4.7 then a document of ~120K is loaded, but none of the links works. Saving the file (from Netscape) and viewing the source provides a textbook example of how not to write JavaScript. (Note that the page works fine under MSIE 4.0 if you alter it so as not to detect IE 4). See how in a page that should have been tailored for non-MSIE browsers there are functions like:
    function doDocumentOnMouseOver() {
            var eSrc = window.event.srcElement ;
        if (eSrc.className == "clsHeading") 
            { eSrc.style.color= "#0033CC" }
      }
    
    using elements like window.event which are MS-proprietary. Included for no extra cost are pearls such as:
    // This part decides if it is IE4 then sends it to the correct page for it
    // Else sends it to the plane[sic] jane, stale cookie page.
    

    Personally, I wouldn't recommend that you go through all the above travail - when I downloaded the reference, I found it to be a miserable small thing in which I found little of value.

  • Coolnerds have a large page comparing many JavaScript terms, and their availability in Netscape and IE.

  • There's some surprisingly concise and well-written JavaScript stuff on the Raven site.

  • Databynet is a good JavaScript 1.2 reference.

  • Here is the ecma 262 specification for 'EcmaScript' - the JavaScript standard.

  • javascript.internet.com is a FAIR REFERENCE

  • STARS - is reasonable.

  • Excellent stuff on JavaScript (MSIE event handling - the preceding section is on Netscape).

Trivia

You might wish to check out a trivial animation demo that uses no frames, layers or animated GIFs. As it is, it requires JavaScript functions to work, but it could be rewritten to even remove this requirement. In a way, it's a test of your browser's ability to quickly and regularly load frames - MSIE generally performs significantly better than NN. (Note that Netscape seems to take ages to clear the page background, so the screen flickers in a really irritating fashion).
Check it out.

Disclaimer
All the code on this and the preceding pages is provided free, and as is. We don't guarantee that it will work, nor do we guarantee that it's suitable for any particular application. You use it entirely at your own risk. If you're having trouble with code, email us and we'll try and help you if we can find the time! If you're unhappy because our code is similar to something you regard as proprietary, talk to us, but most of the above examples are freely available on the Web. We've tried to attribute code samples, where we know the sources. Much of what we wrote was based on the above references; other code was derived from simple experimentation!


Webpage author jvs@anaesthetist.com Last update: 2001-03-03