Trapping Events

As you saw in Chapters 5 and 6, objects in the Object Model fire specific events when certain actions occur. For instance, a button INPUT on a form fires an onclick event when it is clicked, and the window object fires an onerror event when an error occurs. Appendix C provides a complete list of all the events supported in Internet Explorer. Full descriptions of all the events can be found on the SBN Workshop Web site and on the CD that accompanies this book. On the CD see Workshop (References); DHTML, HTML & CSS; DHTML References; Events. To get to the online version, visit the MSDN Online Resource page at msdn.microsoft.com/resources/schurmandhtml.htm, or open the file named MSDN_OL.htm on the companion CD, and choose DHTML Events.

A number of the more common events are supported by both Netscape Navigator and Internet Explorer. These include onclick, ondblclick, onmousedown, onmouseup, onmousemove, onmouseover, onkeypress, onkeydown, onkeyup, and onresize. Netscape Navigator is fairly particular about exactly which events are supported on different objects. For example, HTML elements that support onclick in Navigator 4 are document, A, and INPUT (types button, check box, radio, reset, and submit). Additionally, many elements that support one event do not support others. For example, a button INPUT in a form supports onclick, but not onmouseover. Internet Explorer supports most events (especially the common ones like mouse events) on almost all objects.

An event is not very useful unless script that responds to the event is available. Such script is known as an event handler. Code Listing 7-2 demonstrates a standard method of assigning script to handle a particular event, also known as trapping the event.

Code Listing 7-2.

 <HTML> <HEAD> <TITLE>Listing 7-2</TITLE> </HEAD> <BODY> <FORM onload="alert(`BODY loaded.')"> <INPUT TYPE="button"   VALUE="Click Me"   onclick="alert(`You clicked the button.')"   onmouseover="alert(`You moused over the button.')"> </FORM> </BODY> </HTML> 

One of the easiest ways to trap an event is to use an embedded (also known as inline) event handler (as you saw in Code Listing 6-4). In Code Listing 7-2, an event handler is embedded in both the <BODY> and <INPUT> tags. Inline event handlers are the most widely supported type of event handler, with at least partial support going back several years. Both Netscape Navigator and Internet Explorer will display an alert message when the body loads and when the button is clicked, but Navigator will not display an alert when the mouse passes over the button for reasons detailed above. (If you find that the first dialog box interferes with clicking the button, dismiss that dialog box by pressing the enter key rather than by clicking OK.)

Code Listing 7-3 demonstrates the three common ways of trapping events, not all of which are supported in all browsers. Figures 7-3 through 7-7 illustrate how the code behaves in Internet Explorer. Figure 7-8 shows how a click on the body is handled by Netscape Navigator.

Code Listing 7-3.

 <HTML> <HEAD> <TITLE>Listing 7-3</TITLE> <SCRIPT LANGUAGE="JavaScript"> // If using NS 4+ capture click events (unnecessary in Internet Explorer) if (window.Event){   document.captureEvents(Event.CLICK)   document.onclick=EventInfoNS      // Bind the EventInfoNS function }  else{document.onclick=EventInfoIE}  // Bind EventInfoIE to a click for IE function EventInfoIE(){   // Display what fired the event, its name, the event type, and where   e=window.event   alert("The "+e.srcElement.tagName+" element called "+e.srcElement.id+     " fired the "+e.type+" event. This occurred at screenX="+     e.screenX+" and screenY="+e.screenY+".") } function EventInfoNS(e){   // Display what event happened where   alert("A "+e.type+" occurred at screenX="+e.screenX+" and screenY="+     e.screenY+".") } </SCRIPT> <SCRIPT FOR="Span1" EVENT="onmouseover" LANGUAGE="JScript">   // This code runs when the mouse travels over the SPAN   Span1.innerHTML="You moused over this." </SCRIPT> </HEAD> <BODY ID="theBody"> <IMG ID="Img1" SRC="circle.gif"> <SPAN ID="Span1" onmouseout="this.innerHTML=`You left it.'">   This is the first state. </SPAN> </BODY> </HTML> 

click to view at full size.

Figure 7-3. Initially, the Internet Explorer window looks like this; but as you move the mouse and click it, different events occur.

click to view at full size.

Figure 7-4. When you move the mouse over the text in the SPAN element, the onmouseover event is fired and the text changes.

click to view at full size.

Figure 7-5. When you move the mouse away from the text, the onmouseout event is fired and the text changes again.

click to view at full size.

Figure 7-6. In Internet Explorer, an Alert dialog box indicates that the IMG object was clicked.

click to view at full size.

Figure 7-7. In Internet Explorer, a different Alert dialog box is displayed when the text is clicked.

click to view at full size.

Figure 7-8. The contents of the Netscape Navigator window after the body of the document is clicked.

NOTE
Code Listing 7-3 above uses JScript comments (the lines beginning with two forward slashes). Comments are a useful and highly recommended way of noting the purpose of different parts of your code.

As you can see, an embedded event handler is used in the <SPAN> tag:

 <SPAN ID="theSpan" onmouseout="this.innerHTML=`You left it.'"> 

This code specifies the onmouseout event, and then it binds the script "this.innerHTML='You left it.'" to that event. The keyword this references the current object—in this case, theSpan. Thus, whenever the mouse leaves the SPAN element, that object's innerHTML property is set to the text You left it. Because this property specifies what should appear inside the SPAN element, you will see the new text displayed on the screen. Although Netscape Navigator supports embedded event handlers, it will not actually do anything when the mouse leaves the SPAN element. This is because it does not support onmouseout or onmouseover on SPAN elements, nor does it support changing an element's innerHTML property.

Another way to trap an event is to create a block of script devoted solely to that event, as we did in Code Listing 6-3, and as seen in the first script block in Code Listing 7-3. The script block begins with a standard <SCRIPT> tag and includes a FOR attribute, which specifies the object being tracked, an EVENT attribute, which specifies the event to be handled, and as with all SCRIPT tags, a LANGUAGE attribute:

 <SCRIPT FOR="theSpan" EVENT="onmouseover" LANGUAGE="JavaScript"> 

This block of script runs whenever the object named theSpan experiences an onmouseover event. When you run this code and move your mouse over the text displayed by the SPAN element, the text changes to read You moused over this (as shown in Figure 7-4). This method of trapping events is supported only in Internet Explorer.

You can also trap an event by binding a function to the event. This is supported in both Netscape Navigator and Internet Explorer, though with some differences between the two. To do this, the page must contain a named function. (We introduced functions in Chapter 6, and we will cover them in more depth in Chapter 9.) For example, Code Listing 73 contains two functions named EventInfoNS and EventInfoIE.

In Netscape Navigator, you must first notify the browser that you want to capture click events with the captureEvents method, so we first check whether Navigator is being used, capture the click event, and then bind the EventInfoNS function to the event with the following code.

 if (window.Event){   document.captureEvents(Event.CLICK)   document.onclick=EventInfoNS     } 

An if statement is used to determine whether the window object has a child object named Event. (You'll find more detail about if statements in Chapter 9.) This will be true only in Netscape Navigator version 4 and later (a similar object in Internet Explorer is named event, with a lowercase "e"). If the window object contains such an object, click events are captured and the EventInfoNS function is bound to the event.

In Internet Explorer, there is no need to state explicitly that we want to capture the event, since almost all events are automatically captured. In fact, because it is not supported, the captureEvents method will cause errors in Internet Explorer. This is why the previous test was performed. The following code causes the EventInfoIE function to be run whenever the onclick event is fired by the document object in Internet Explorer:

 document.onclick=EventInfoIE 

Note that the syntax for actually binding a function to an event is the same between browsers.

Let's take a deeper look at the EventInfoIE function in Code Listing 7-3, which is used by Internet Explorer. The listing contains the following code, which displays an Alert dialog box containing information about the element that was clicked.

 e=window.event alert("The "+e.srcElement.tagName+" element called "+e.srcElement.id+   " fired the "+e.type+" event. This occurred at screenX="+   e.screenX+" and screenY="+e.screenY+".") 

In Internet Explorer the window object has a child object named event, which is available when an event is occurring (and only exists for the duration of that event). We first assign this object to a variable named e. This step is not required but makes it easier to refer to the object later in our code and results in code that performs faster than specifying the entire hierarchical object name every time. The event object has a variety of useful properties. For example, its srcElement property specifies the particular object that fired the event. The alert code above uses srcElement to retrieve information about the type of tag that fired the event, the tag's name, and the type of event fired. Other properties of the event object report information such as the position of the mouse on screen (screenX and screenY), the position of the mouse relative to the top left of the browser window (clientX and clientY), and the identity of keys pressed. You can see this function in action by clicking anywhere on the Web page—on the image, on the text, or even on the blank background area. Notice that the Alert dialog box displays the tag name of whatever item is clicked, even though the onclick event is bound only to the document object. This is a result of event bubbling, explained in the next section.

The EventInfoNS function, used by Netscape Navigator, takes a single parameter e used to represent the Event object. Navigator's Event object supports a number of properties, including screenX, screenY, type, pageX, pageY, target, and several others. This function will display an alert of the type of event that occurred and where it occurred on screen. Note that the function is only called when the body itself (not the text or image) is clicked.

Event Movement Through the Object Model

Netscape Navigator and Internet Explorer have very different ways of communicating events through the Object Model. As described in Chapter 5, when an event occurs to an object in Internet Explorer, the event "bubbles up" through the Object Model hierarchy until it either reaches the top or is explicitly cancelled. Because the document object is further up the hierarchy than all visible objects on an HTML page, any click on any object is reported to it. Thus, an onclick event handler on the document object will respond to any click on any object. Event bubbling in this fashion is a standard way of communicating events in many operating systems and development environments.

Netscape Navigator behaves in exactly the opposite fashion: events travel from the top of the object hierarchy to the bottom. At the top, the event is captured as shown in Code Listing 7-3. If you want the event to be processed by some object further down the hierarchy, you can use the routeEvent and handleEvent methods to direct travel of the event. More information about this can be found at developer.netscape.com. An excellent tutorial in the Netscape Navigator Object Model can be found at webreference.com, where you will also find many useful articles, including a comparison between the Object Models in Internet Explorer and Netscape Navigator.

Sometimes you will not want an event to bubble up to the parent of an object in Internet Explorer. For example, we might want the image in Code Listing 7-3 to react to a click differently than does every other element on the page. We could accomplish this by adding the following event handler to the image in Code Listing 7-3:

     onclick="alert(`I react differently.');window.event.cancelBubble=true"> 

Figure 7-9 shows the new results when the image is clicked.

click to view at full size.

Figure 7-9. Clicking the image now generates this display rather than the one shown in Figure 7-6.

Now when the image is clicked, its own embedded event handler displays an alert and then sets the cancelBubble property of the event object to true. This prevents the event from bubbling up to parent objects. As a result, the document object does not receive the onclick event when the image is clicked, and the displayEvent function is not executed. The document object can still receive onclick events from the other objects on the page, however, because they have not canceled event bubbling.

Event bubbling can be both a great timesaver and a big pain. Allowing one handler to trap events on several objects can save coding work, but it can sometimes result in confusion when you do not want a particular object's event to have an effect. Appendix A presents some examples of this problem as well as some workarounds.

NOTE
When using event bubbling, it is almost always better to use the document object instead of the window object. This is because many of the events that bubble up to the document object do not go on to the window object.



Dynamic HTML in Action
Dynamic HTML in Action
ISBN: 0735605637
EAN: 2147483647
Year: 1999
Pages: 128

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net