Приглашаем посетить
Грин (grin.lit-info.ru)

9.3 Setting up general event handlers

Table of Contents

Previous Next

9.3 Setting up general event handlers

9.3.1 Event models of browsers

An event model is the inside structure of a browser used to handle events. Unfortunately, different browsers, such as IE and NS, in general have different event models. This section discusses such models and shows how to set up event handlers or listeners for each of them.

In normal circumstances, you don't need to consider event models in your Web page design. However, if you have a dynamic Web page and the behavior of IE and NS browsers is different and drives you mad, you may need to consider the event model structure of the browser.

IE introduced the concept of so-called event bubbling as the event model. This contrasts with NS4.x where events dive from the window object to the target object. From the object tree of a general page (see Fig. 9.12), you can see the event diving, or descending, structure.

Figure 9.12. Object tree of a Web page

graphics/09fig12.gif


During event diving, the event can be intercepted and processed at any level from window to target.

An event in the IE family, on the other hand, bubbles outward from the target object to the window object, walking through all the involved objects and levels along the way. At each upward level, the object can intercept the event and process it. The order of event interception is determined by the upward order. This action is similar to a bubbling effect and the model is therefore called the "Bubbling Event Model." The target object is always first, followed by any higher level in the hierarchy. Consider again example ex09-06.htm. Any button click generates an onclick event starting at the target button and then traveling upward to the body and captured by the body onclick handler. This is typical event bubbling. To prevent the onclick handler inside the <body> from moving the picture, a detection variable is employed.

Yes, you are right! Example ex09-06.htm will perform differently on NS4.x from the theory of a diving event model. More precisely, when a button is clicked, the mouseClk() function runs first and drives the picture to the button position before changing the next selected picture. However, this example runs properly on NS6+, because NS6+ also supports the bubbling event model.

NS6+ has its own unique and interesting event model which combines the diving model of NS4.x and the bubbling model of IE. Events in NS6+ propagate outward from the target object to the browser window and also can be set as in the diving model. Any object in the hierarchical direction can capture the event before it reaches the other end. That is, NS6+ supports both directions and you can specify whether you want to intercept the event during its diving phase or its bubbling phase.

To demonstrate these behaviors, let's consider some simple examples.

9.3.2 A page to test event models

To test the event model of a browser is quite straightforward. The basic idea is to detect which object or level captures the first event. If the first event is captured at the target object, the event model is "Bubbling." Otherwise, the model is a "Diving" type. However, for backward compatibility and to develop an event model page to test IE5.x, NS6.x, and NS4.x, a classical technique that combines form and anchor is used. The XHTML coding of this page is



Example: ex09-07.htm - A Page To Test Event Model

 1: <?xml version="1.0" encoding="iso-88591"?>
 2: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 3:     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 4: <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
 5: <head><title> A Page To Test Event Model - ex0907.htm </title></head>
 6: <script src="ex0907.js"></script>
 7: <body style="background:#dddddd;font-family:arial;font-size:20pt;
 8:             color:#000088;font-weight:bold">
 9: <div align="center" >Test Event Model<br /><br />
10: <form action="" id="myform" name="myform">
11:   <a href="javascript:targetClk()" style="font-family:arial;
12:      font-size:18pt;font-weight:bold" onClick="targetClk()" onmouseout=
13:      "outsideTarget()" onmouseover="insideTarget()" >Press Me</a>
14:                           <br /><br />
15:   <input type="text" id="outMsg" name="outMsg" style="font-family:arial;
16:      font-size:18pt;font-weight:bold;width:340px;height:40px"
17:      value="Please Click The Text Above" />
18: </form></div>
19: </body>
20: </html>

This is a form application so that the text input in lines 1517 can be displayed correctly in some older browsers. To demonstrate a comprehensive technique, an anchor element is employed to trigger the event. The onmouseover and onmouseout event handlers are used to restrict the mouse click to occur inside the target object so that the internal operations of the browser can be tested properly. The external script file ex09-07.js mentioned in line 6 is listed as follows:



Example: ex09-07.js - The ECMAScript For ex09-07.htm

 1:   var IE=document.all?true:false
 2:   if (!IE) document.captureEvents(Event.CLICK)
 3:   document.onclick=mouseClk
 4:
 5:   var modelV =0           // 1 - Diving Model, 2 - Bubbling Model
 6:   var insideTar = false
 7:   var outSt = new Array()
 8:   outSt[0]="Please Click The Text Above"
 9:   outSt[1]="Diving Event Model"
10:   outSt[2]="Bubbling Event Model"
11:
12:   function mouseClk()
13:   {
14:     if (modelV ==0) modelV=1
15:     if (!insideTar) {
16:           modelV=0
17:           outputMsg(0)
18:     }
19:   }
20:
21:   function targetClk()
22:   {
23:     if (modelV ==0) {
24:             outputMsg(2)
25:             modelV =2
26:    }
27:    if (modelV ==1) outputMsg(1)
28:   }
29:
30:   function outputMsg(stV)
31:   {
32:     document.myform.outMsg.value=outSt[stV]
33:   }
34:
35:   function insideTarget()
36:   {
37:     insideTar = true
38:   }
39:   function outsideTarget()
40:   {
41:     insideTar = false
42:   }

The first three lines are used to set up the mouse click event. The variable modelV stores the event model of the browser. The insideTar variable together with the functions insideTarget() and outsideTarget() determines whether or not the mouse click occurs inside the target. If not, the click event is generally ignored. If a click event occurs at the target and modelV=0, the event model is a bubbling type. The outputMsg(2) function in line 24 displays the text "Bubbling Event Model" to the text area with name="outMsg". If modelV=1, this means the event is diving from the mouseClk() function to the target and therefore is a diving model. The text "Diving Event Model" is then displayed by the statement in line 27. Some screen shots of this example on NS4.x and NS6.x are shown in Figs 9.13 and 9.14.

Figure 9.13. Event model of NS4.x

graphics/09fig13.jpg


Figure 9.14. Event model of NS6.x

graphics/09fig14.jpg


9.3.3 Setting up event handlers and listeners

There are a number of ways to set up event handlers. The first one, and possibly the most popular one, is to use standard handlers such as onclick, onmousemove, onkeypress, etc., inside an XHTML element. Another one is to use the script without any handler references in the page element. For example, the following code can be used to set up an event handler on the document body:



var IE=document.all?true:false
if (!IE) document.captureEvents(Event.CLICK)
document.onclick=mouseClk

This handler will listen to any click event on the document body and redirect the event to the function mouseClk(). The main characteristic of this code is that you don't need to put the standard handler onclick="mouseClk()" inside the body element. If you are using a W3C-compliant browser, you can ignore the first two statements. Only the statement document.onclick= mouseClk is needed to set up an event handler on the document body. In fact, event handlers can be set up this way on most of the XHTML elements. Thus if you have an object on a page such as



<div id="obj01" name="obj01"
  style="font-family:arial;font-size:18pt;font-weight:bold;
  background:#ffff00;position:absolute;top:80px;left:250px;
  width:100px;height:40px" />Obj01</div>

you can set up an onclick event handler using a simple script:



<script>document.getElementById("obj01").onclick = obj01Clk</script>

This way, you can set up event handlers entirely by using script. Again, you can see that the standardization and the efforts of W3C have made life elegantly simple: all programming can be done in one format.

Perhaps another more advanced method to set up an event handler is to use a"listener." An event listener is actually a function to listen to events and attach them to a specific action. Unfortunately, IE and NS have different event listener functions.

To set up an event listener on IE for the obj01 example, you can use the following code:



objClk = document.getElementById("obj01")
objClk.attachEvent("onclick",myClk)

The main idea is to get an element and to attach it to an event using the event listener. The event listener function attachEvent() was first introduced in IE5.x to attach an element any event. In this case, the browser will listen to any onclick event and redirect control to the function myClk(). One of the strengths of the event listener is that you can attach many actions to the same event for the same object. For NS6+, the same event listener is



objClk = document.getElementById("obj01")
objClk.addEventListener("click", myClk, false)

First, you have a different function name for the listener. Second, in order to use this addEventListener() properly, you don't include the "on" prefix for the event names you need to use mousemove, mousedown, keypress, etc., instead. Finally, the listener has a third Boolean argument. This Boolean variable is used to instruct the listener which event model should be used. A true value signals the listener to use the diving event model and the bubbling event model otherwise. The addEventListener() function is a standard function recommended by W3C. In order to gain more experience and to put these into action, consider some popular and practical techniques for moving objects.

    Table of Contents

    Previous Next