Home Articles FAQs XREF Games Software Instant Books BBS About FOLDOC RFCs Feedback Sitemap
irt.Org

Related items

Man-Handling Events #3

Man-Handling Events #2

Events and Event Handlers

Man-Handling Events #1

You are here: irt.org | Articles | JavaScript | Events | Man-Handling Events #1 [ previous next ]

Published on: Monday 25th October 1999 By: Ryan Detert

Introduction

The latest versions of Netscape Communicator and Microsoft Internet Explorer offer an incredible amount of versatility to the programmer compared to the browsers of yore. Events, their handlers in particular, have given web pages a more robust, interactive environment. Explorer's latest version, 5.0, is the best equipped with event handlers, as you may handle any event from printing to pasting. In this article we will explore the events in both Netscape Communicator 4.0 and Explorer 4.0+ that deal with the mouse and keyboard.

Event vs. Event Handler

Briefly, an event is anything that triggers something within the browser. For example, a mouse click or a key press are seen as events by the browser. When these events occur, you may tell the browser to do something via the event handlers.

An event handler is really what we will be concerning ourselves with because without these the events would not trigger anything. An event handler always has the prefix on. So, to capture a click event in Explorer we can use the associated event handler onclick and to capture a key press we can use the event handler onkeypress. Simple.

Note that when page elements are set up to trigger certain events, this is known as binding because you are literally binding the events to the page elements. It is an important term that you will hear a lot.

Netscape vs. Explorer

Netscape and Explorer both handle essential events such as reading mouse clicks and key presses. However, there are a wide range of differences in the way you handle the events in each browser.

Not to bias you in any way, but before we begin I will take the time to make these general statements. Explorer handles all the types of events that Netscape does and many, many more. In addition, the event handling capabilities of Netscape are generally limited as you may only apply them to few objects such as the document or window, whereas, Explorer allows you to apply event handlers to every element within the HTML document!

The Document Object Model

The Document Object Model is an object tree that is made up of any number of nodes. To sound fancy, the DOM defines an object hierarchy. Each node has the ability to have child nodes. Conversely, every node (except the root) has a parent node. The idea of nodes in HTML can best be explained by examining how a simple table is created. For example, we could use the following code:

<table>
	<tr>
		<td></td>
		<td></td>
	</tr>
</table>

In a table the <table> element is the parent (node) of the <tr>s and <td>s. Likewise, the <tr>s are still the parents (node) of the <td>s, however, it is also the child (node) of the <table> element. Moreover, the <td>s have no children (leaf nodes) but are still children to both the <table> and <tr> elements.

Essentially, that is all the DOM hierarchy is, a cascade of parents and their children. But do realize that this hierarchy was not created for HTML, but rather for scripting so that the programmer would have access to all objects and elements throughout the HTML document.

Fire Burn and Cauldron Bubble

As explained in the previous section, every object is a node of some sort, whether it be a parent or a child. When an event is triggered in Explorer 4.0+, the event will move (bubble) up the DOM hierarchy until it reaches the root node, the window object. Netscape 4.0 does not use bubbling.

The concept of bubbling is not new and is used in most operating systems. This offers many advantages to the programmer. For instance, bubbling allows multiple objects to handle the same event and it ultimately makes code cleaner and more efficient.

Bubbling can be regulated by the programmer by using the window.event.cancelBubble event object property. Setting this to true will stop the event from bubbling up the hierarchy, whereas setting it false, the default, will allow the event to continue bubbling. View the following examples to see exactly what I mean.

Click Item 1

Click Item 2

Click Item 3

In this example Item 1 is the parent of both Item 2 and 3. Item 2 is a child of Item 1 but a parent of Item 3. Item 3 is a child of both Item 1 and 2.

Notice that when you clicked Item 3 all the onclick handlers for the parents of Item 3 are also triggered. This is known as bubbling, where the event moves (bubbles) up the hierarchy. The user's click event moves all the way up the hierarchy until the window object, which is at the top of the DOM hierarchy structure.

<style>
#first {color: orange; cursor: hand}
#second {color: red; cursor: hand}
</style>

<div onClick="alert('Item 1 clicked')"><h1 id="second">Click Item 1</h1>
    <div onClick="alert('Item 2 clicked')"><h2 id="second">Click Item 2</h2>
        <div onClick="alert('Item 3 clicked')"><h3 id="second">Click Item 3</h3>
        </div>
    </div>
</div>

Click Item 1

Click Item 2

Click Item 3

This example is set up the same as the previous example except this time I used the window.event.CancelBubble property to stop the click event from moving up the hierarchy.

<style>
#first {color: orange; cursor: hand}
#second {color: red; cursor: hand}
</style>

<div onClick="alert('Item 1 clicked'); window.event.cancelBubble=true"><h1 id="second">Click Item 1</h1>
    <div onClick="alert('Item 2 clicked'); window.event.cancelBubble=true"><h2 id="second">Click Item 2</h2>
        <div onClick="alert('Item 3 clicked'); window.event.cancelBubble=true"><h3 id="second">Click Item 3</h3>
        </DIV>
    </DIV>
</DIV>

Capturing Events Netscape Style

Utilizing events is a bit more cryptic and tedious than with Explorer, however, it is possible in many circumstances. The only problem with Netscape is that events can only be binded with a select group of objects, mainly layers, windows, and documents, whereas, Explorer permits binding with any object on your page.

Netscape utilizes a primary method of capturing events that is aptly named captureEvents(). This method takes bit-flagged arguments that Netscape provides logical aliases for (e.g. Event.MOUSEDOWN). The captureEvents() method can be used with all event handlers, however it is only compulsory with all mouse events.

For example, to capture all MouseUp's and MouseDown's we must first alert Netscape as to which events we would like to capture by going something like: window.captureEvents(Event.MOUSEDOWN | Event.MOUSEUP). Notice the use of the bit-wise OR operator to separate event types. We then would assign the event to a specific object by going something like: window.onMouseDown = myFunction.

To clear up any confusion the finished code would look like this:

function myFunction(e) {
    alert('Something Was Pressed!');
}

window.captureEvents(Event.MOUSEDOWN | Event.MOUSEUP);
window.onMouseDown = myFunction;

A Note On Syntax

All event handler will be pre-fixed with the word 'on'. For instance, the event handler for the click event is 'onclick.' When using these in scripting, as you will see below, you MUST remember that MSIE is CASE-SENSITIVE! MSIE requires all even handlers in scripting to be LOWERCASE letters, whereas Netscape is NOT fussy in this regard.

Assigning Events

In general, to handle events there are two ways that work in both browsers. One way uses inline HTML while the other uses scripting. The general syntax, where onEvent pertains to a handler such as onclick, is as follows:

Explorer offers yet another way of initializing event handlers that is called a named script. Its syntax is as follows:

In Explorer, whenever an event is handled, the event information moves up the DOM hierarchy and ultimately ends up with the window.event property unless previously cancelled. Once this happens you can then access the event from anywhere on the web page by using the window.event property.

In Netscape the event passes the information as an argument to the function that is handling the event. For example, if you had:

function clickHandle(myClicks) { ... }
...
...
document.onclick = clickHandle;

The information from the mouse would be contained in the user-defined variable object myClicks. Then, for example, to retrieve the type of event from within the clickHandle() function you could go: myClicks.type.

Making Events Useful Via Event Object Properties

After you have captured an event you have the ability to attain specific information dealing with the event via event object properties. For example, when a key is pressed, the keyboard information is passed to an object or property of some sort. At this point you have no clue which key has been pressed. So, to the obtain actual key that was pressed you must use an event object property like so:

window.event.keyCode (Explorer)
userObject.which (Netscape)

Here are the event object properties for each browser.

Explorer:

Netscape:

Advanced Netscape Features

Netscape offers five other advanced methods of event handling that we have not yet looked at. You may never have to use them but it is nice to know they're handy.

releaseEvents()

releaseEvents() - applies to window, document, and layer objects.

Works in the same manner as the captureEvents() method except this disables the event handlers.

routeEvent()

routeEvent() - applies to window, document, and layer objects.

After calling this method JavaScript looks down the hierarchy for other event handlers that may be handling the same event but are registered with different objects. For example, window.onClick and document.onClick are both trying to handle the same click event, Netscape will route the event over to the document.onClick because it is lower on the hierarchy. If no conflicts are discovered, the current, original object will then handle the event. This method will return the value returned by the event handler.

handleEvent()

handleEvent() - applies to window and document objects.

With this method you can make one object handle all of one type of event. For example, if you went window.onClick = myClickHandler, then, in the myClickHandler() function you could go:

function myClickHandler(myObject) {
    window.document.links[0].handleEvent(myObject);
}

This means that all clicks will be handled by the first hyperlink in the document. This is also granted that you have given the link an onClick handler like

<a href="link.html" onClick="handler" ...>...</a>

enableExternalCapture()

To allow a window with frames to capture events in pages loaded from different locations (i.e. servers). You may call this method before using the captureEvents() method.

disableExternalCapture()

Call this method do disallow a window to capture events within its frames.

Related items

Man-Handling Events #3

Man-Handling Events #2

Events and Event Handlers

Feedback on 'Man-Handling Events #1'

©2018 Martin Webb