Introduction of Events In DHTML

“Events are the heart of any JavaScript application. Events are used to add interactivity to the page. Without events interactivity can not be imagined.”
 
The Web is an ever evolving environment, and Web pages themselves are steadily blooming from static displays of data to interactive applications. “Dynamic HTML” is an umbrella term encompassing several ways in which Web developers can breathe life into pages which have traditionally been still portraits of information.
 
The basic notion behind Dynamic HTML is quite simple: allow any element of a page to be changeable at any time. Sounds like a dream, but as with any simple plan, “God is in the details,” as they say. In the olden days, you could only change content on a page via CGI.
 
This required a server to perform the changes to the page and re-serve the entire page, modifications and all, back to the client. While workable, this process was quite slow, as it placed a burden on both network traffic and server processing time. With long delays between a user’s action and an on-screen response, building effective Web-based applications was quite constricting.
 
With DHTML, the magic occurs entirely on the client-side. This means that page modifications should appear immediately following a trigger, such as a user selection. And, remember, the DHTML dream is that you can modify any aspect of the currently loaded page — text styles, swapped images, context-sensitive forms and tables, and even the on-screen data itself.
 
It’s worth noting here, then, that “Dynamic HTML,” isn’t really about HTML, the markup language. By and large, DHTML describes the abstract concept of breaking up a page into manipulable elements, and exposing those elements to a scripting language which can perform the manipulations.
 
The degree, or fineness, to which these elements are defined and actionable is a function of DHTML’smaturity. Because we’re only seeing the second generation of browsers supporting DHTML (MSIE 5 and the upcoming Netscape 5 based on Mozilla), DHTML is still an evolving and at times, inconsistent set of tools.
 
Without events there are no scripts. Take a look at any web page with JavaScript in it: in nearly all cases there will be an event that triggers the script. The reason is very simple. JavaScript is meant to add interactivity to your pages: the user does something and the page reacts.
 
Therefore JavaScript needs a way of detecting user actions so that it knows when to react. It also needs to know which functions to execute, functions that do something that you, the web developer, have judged likely to increase the appeal of your pages. These pages describe the best way to write such scripts. It isn’t easy, but it is very satisfying work.
 
When the user does something an event takes place. There are also some events that aren’t directly caused by the user: the load event that fires when a page has been loaded, for instance.
 
JavaScript can detect some of these events. From Netscape 2 onwards it has been possible to attach an event handler to certain HTML elements — mostly links and form fields in the early days. The event handler waits until a certain event, for instance a click on a link, takes place. When it happens it handles the event by executing some JavaScript you have defined.
 
When the user takes action he causes an event. When your script makes the page react to this event, interactivity is born.
 
History of event handling
 
As I said, without event handling there is no point in adding JavaScript to your pages. The best scripts are those that react to something the user does. Therefore, when Netscape released its Version 2 browser which supported JavaScript, it also supported events.
 
Netscape model
 
Netscape 2 supported only a few events. Mouseover and mouseout quickly became famous because of the legendary mouseover effect that changed images onMouseOver and changed them back onMouseOut. It was also possible to see if the user submits or resets a form, so that client–side form validation became possible.
 
The browser could also detect if a form field receives or loses the focus or if the page has finished loading or starts unloading. Although by present standards this is very basic behavior, at that time it was a revolutionary extension of the possibilities of Web pages. True interaction became possible because you could react to user actions.
 
In its most ancient form an event handler looks like this. When the user clicks on this link, the event handler is executed and the alert pops up.
 
 
<a href=”somewhere.php” onclick=”alert(‘I\’ve been clicked!’)”>
 
It is very important to realize that this ancient way of event handling was de facto standardized by Netscape. All other browsers, including Explorer, had to conform to the way Netscape 2 and 3 handled events if they wanted JavaScript to work. Therefore these ancient events and event handlers work in all JavaScript browsers.
 
Modern event models
 
However, since the introduction of these simple event handlers much has changed. First of all the number of events has increased. Also, the way of registering event handlers to HTML elements was changed. They can now be set entirely through JavaScript. No more need for huge numbers of event handlers cluttering up your code, now you could write a simple script that sets all event handlers for you.
 
The Version 4 browsers also provided more information about the event itself. Where was the mouse when the event happened? Was any key pressed? Finally, browser vendors had to decide what happened when an element and its parent element both had a handler for the same event. Which event fires first?
 
Since this functionality was added at the height of the Browser Wars, Netscape and Microsoft made a distinct point of creating totally incompatible event models. More recently a third model has appeared on the scene when W3C published its DOM Event specification.
 
Despite one serious flaw, W3C’s model, which is loosely based on the old Netscape model but much more generalized and versatile, is an excellent piece of work, adding lots of new interesting functionalities and solving a lot of problems of older event models.
 
Of course the existence of three models means that event handling doesn’t work the same way in all browsers.
 
The Event Connection
 
Quite frequently, you want some type of trigger to cause your DHTML to kick in. Whether repositioning blocks or changing style properties, some event usually causes these changes.
 
Many different types of event can occur on a Web page, most of them caused by the user. He or she might click on a button (click event), might move the mouse over an element (mouseover event), or move the mouse off of an element (mouseout event).
 
 
The user may submit a form (submit event) or resize the browser window (resize event). Additionally, some events occur without direct user intervention — the page may finish loading (load event), for example.
 
Events, although an intrinsic part of DHTML, are not part of the standard DOM Level 1 specification. Consequently, event handling between Microsoft and Netscape browsers can vary enormously in practice. The DOM Level 2 specification does include events, but unfortunately as of this writing, DOMLevel 2 support in both major browsers is still more of a dream than a reality.
 
Managing events can be relatively simple or quite complex, depending on the ambitions of your project. Since this is an introduction, we’ll focus mainly on event basics. Fortunately, basic events are handled most similarly between browsers.
 
Event Handlers
 
Events occur on a Web page whether you choose to act on them or not. When the user moves the mouse over an element, a mouseover event occurs. If you would like to leverage this event as a trigger for some dynamic action, you must construct an event handler.
 
An event handler is created as an attribute for the tag which defines the element at which you wish to catch the event. Event handler attribute named follow the syntax onEventname, and they accept JavaScript statements as their action. For example, the following tag creates a hyperlink with a mouseover event handler specified.
 
<A HREF=”page.php” onMouseOver=”changeStatus(‘Read this page’);”>Click here</A>
 
The onMouseOver event handler catches a mouseover event. When this event occurs at this element, a JavaScript function is called named changeStatus(). This is a fictional function,
 
you can imagine that it might exist to change the message on the browser’s status bar. Any JavaScript statement is allowed in an event handler, so we could also execute direct statement rather than call a function. For example, suppose that a mouseover for this element in MSIE should modify a style sheet’s color property:
 
<A HREF= “page.php”onMouseOver=”document.styleSheets[0].rules[0].color=’blue'”>Click here</A>
 
The above example assumes MSIE, since live style sheet modifications aren’t supported in Netscape. We also assume that a style sheet exists in this document! But, hey, it’s just an example.
 
Once again, a convenient table will help summarize the common event and their event handler names.
 
Event Event Handler Syntax Description
     
click onClick User clicks (left) mouse button on an element.
submit onSubmit User submits a form, this event fires
before the form submission is processed.
reset onReset User resets a form.
focus onFocus User brings focus to an element either
via mouse click or tabbing.
blur onBlur User loses focuses from an element
by clicking away or tabbing away.
mouseover onMouseOver User moves mouse over an element.
mouseout onMouseOut User moves mouse off of an element.
mousemove onMouseMove User moves mouse.
change onChange User changes value in a text, textarea,
or select field.
select onSelect User selects (highlights) a portion of text
in a text or textarea field.
resize onResize User resizes browser window or frame.
move onMove User moves browser window or frame.
load onLoad Page completes loading.
unload onUnload User exits page (by navigating to a new
page or quitting browser).
error onError An error occurs loading an image or document.
abort onAbort User stops an image loading using the stop button.
 
The above table is a quick reference guide. There are some important caveats to keep in mind. For one, this is not a comprehensive list of all events, although these are by far the most commonly used. Both browser support additional events for detecting keypresses and other mouse actions, while MSIEsupports additional events above and beyond Netscape’s.
 
Secondly, you must keep in mind that not every event is applicable to every element. This also varies between browsers. For example, within Netscape a mouseover event only applies to a hyperlink <A>, area <AREA> or layer <LAYER>. Yet, within MSIE, you can apply a mouseover event to almost any element, including images <IMG>, and paragraphs <P>.
 
Browser compatibility problems
 
There we go again. As with DHTML, the W3C DOM or other advanced scripting techniques, we have to take care to execute specific bits of code only in those browsers that understand them.
 
Calling stopPropagation() in Explorer or srcElement in Netscape would give horrid errors and would ensure our script’s uselessness. Therefore we must first check if the browser supports the methods or properties we want to use.
 
if (Netscape) {
use Netscape model
}
else if (Explorer) {
use Microsoft model
}
 
is only a first approximation of a solution since it leaves out the minor browsers. The most recent ones can handle a fair amount of modern event handling, unless your script in its infinite wisdom decides that the minor browsers should not be allowed to even try to run the code because they are not Netscape or Explorer.
 
All minor browsers have had the unenviable task of deciding which event model to support. Konqueror/Safari, as always, has opted for strict standard compliance and supports the W3C model. Opera and iCab have been more cautious and support the larger part of both the old Netscape model and the Microsoft model. I haven’t yet studied the minor minor browsers.
 
But a minor minor browser might support the Microsoft way of accessing an event, while the actual event properties are a mix of the W3C and the old Netscape model. This should be no problem, after all the browser follows well known patterns in its own way. Your scripts should be ready for it.
 
Writing an event handling script
 
So how do you write an event handling script? On this page I give a quick overview for those who need fast answers and want to study the theory later.
 
Registering an event handler
 
The first step is registering your event handler. You have to make sure that the browser executes your script whenever the event you’ve chosen takes place.
There are four models for registering event handlers. Inline, traditional, W3C and Microsoft. It’s best to use the traditional model, since it is completely cross–browser compatible and gives much freedom and versatility. To register an event handler, do
 
element.onclick=doSomething;
if (element.captureEvents) element.captureEvents(Event.CLICK);
 
Now the function doSomething() is registered as the handler of the click event of HTML element element. This means that whenever the user clicks on the element, doSomething() is executed.
 
Accessing the event
 
When you’ve registered your event handler you start writing the actual script. Usually you want to access the event itself, so you can read out information about the event.
 
To access the event so that you can read out its properties, always start your event handling function thus:
 
function doSomething(e) {
if (!e) var e = window.event
// e refers to the event }
 
Now e refers to the event in all browsers and you can access the event.
 
Accessing the HTML element
 
Sometimes you also want to access the HTML element the event took place on. There are two ways for doing this: using the this keyword or using the target/srcElement properties.
 
The safest way to access the HTML element is by using the this keyword. this doesn’t always refer to the correct HTML element, but in combination with the traditional model it works fine.
 
function doSomething(e) {
if (!e) var e = window.event }
// e refers to the event
// this refers to the HTML element which currently handles the event }
 
The target/srcElement properties contain a reference to the HTML element the event originally took place on. Very useful, but when the event is captured or bubbles up the target/srcElement doesn’t change: it’s still the element the event originally took place on. (See the Event properties page for target/srcElement, see the this page for the this keyword)
 
Event Bubbling
 
The DOM event model provides for this using a concept called event bubbling. For example, suppose an onclick event handler were assigned to the DIV tag above. Clicking on the link would fire the event first on the A element, it would then “bubble” up to the containing P element and then up to the DIV where the handler function would be called.
 
It’s possible for the handler to cancel the event, but assuming it doesn’t the event would continue bubbling on up to the document root and finally, the browser would follow the default action of loading the link’s URL in the window.
 
Note that the P element could also have had an onclick event handler set, as could any elements above the DIV in the document tree. All of these handlers would be called in turn as the event bubbles up to the document root.
 
This is known as the bubble phase in the DOM event model. Not all events bubble, for example onfocus and onblur do not. Likewise, not all bubbling events can be canceled, stopping the propagation. You can determine which events bubble and can be canceled either by looking up the documentation for the event or, as we’ll see, using the Event object.
 
The Event Object
 
Within an event handler, you can do pretty much anything you want with your script code. Chances are, you’ll want to perform some action related to that event depending on one or more factors.
 
Recall that event handlers are passed one argument, an Event object. It provides several properties describing the event and its current state. You can use these to determine where an event originated from and where it currently is in the event flow. Or use the methods it provides to stop the event from flowing on and/or cancel the event.
 

Event Properties and Methods

Property Name Description
bubbles A Boolean value indicating whether or not the event bubbles.
cancelable A Boolean value indicating whether or not the event can be canceled.
currentTarget The node that this event handler is assigned to.
eventPhase An integer value indicating which phase of the event flow this event is being processed in. One of CAPTURING_PHASE (1), AT_TARGET (2) or BUBBLING_PHASE (3).
target The node that the event originated from.
timeStamp The time the event occurred.
type A string indicating the type of event, such as “mouseover”, “click”, etc.
Method Name Description
preventDefault() Can be used to cancel the event, if it is cancelable. This prevents the browser from performing any default action for the event, such as loading a URL when a hypertext link is clicked. Note that the event will continue propagating along the normal event flow.
stopPropagation() Stops the event flow. This can be used on either the capture or bubble phase.
 
Note that using preventDefault() or stopPropagation() affects only the current, active instance of an event.
 
Internet Explorer
 
As mentioned earlier, IE does not currently support the W3C Event model. Instead of passing an Event object to a handler function, it provides a single, global object named window.event which contains much of the same information.
 
Unfortunately, the property names defined for this object do not match the standard model. Below is a table of equivalent properties in these two models.
 
Internet Explorer Equivalents
W3C Standard IE window.event Notes
currentTarget none See below.
eventPhase none Not applicable in IE.
target srcElement The node that the event originated from.
timeStamp none Not available in IE.
type type Equivalent to the standard.
preventDefault() returnValue Set to false to cancel any default action for the event.
stopPropagation() cancelBubble Set to true to prevent the event from bubbling.
 
To get the equivalent of the currentTarget property in IE, use the this keyword as an argument when setting the event handler in a tag.
 
<a href=”…” onmouseover=”myHandler(event, this);”>…</a> function myHandler(event, link) { … }
 
Note that cancelBubble and returnValue are Boolean properties, not method calls. Setting an appropriate value on these is equivalent to calling stopPropagation() or preventDefault() respectively.