ptg 15.8 Event Handling and the DOM 661 15.8 Event Handling and the DOM 15.8.1 The HTML Inline Way We have been using event handlers like onClick, onSubmit, onMouseOver, throughout this text. In fact, Chapter 13, “Handling Events,” described in detail all of the different event handlers and how to use them. They are the oldest and simplest way that is browser compatible. The following example uses the onClick handler as an attribute of the button element. When the user clicks the button, the function movePosition() will be called. <input type="button" value="move text" onClick="movePosition()"/> But using this type of handler violates the principle of separation of the layers; that is, the separation of markup from JavaScript. 15.8.2 The Scripting Way To keep the markup and the JavaScript separate, the JavaScript provided a way for pro- grammers to apply properties to any object in the HTML tree. In the following example, the onLoad event property is applied to the window object so that when the document has completed loading the function assigned to that object will be triggered. In this example the background color will be changed to light green. See Chapter 13 for details if you need to be refreshed on this traditional model for handling events. Figure 15.32 A scrolling marquee continues to print news across the image. From the Library of WoweBook.Com ptg 662 Chapter 15 • The W3C DOM and JavaScript window.onload=function(){ document.getElementById("bdy").style.backgroundColor="lightgreen"; } 15.8.3 The DOM Way The W3C Dom Level 2 standardized the event model to solve compatibility problems between browsers. Most modern browsers (Mozilla, Opera, Safari, Chrome and Kon- queror) are W3C compliant, except Microsoft Internet Explorer which has its own model. DOM objects can be registered as event listeners. This feature can be used to assign multiple handlers for a given event which is the main difference from the traditional model. To achieve this, event listeners are no longer stored as HTML attribute values but are registered with an event listener method. The W3C supports event bubbling described below, but has a useCapture option can be used to specify that the handler should be called in the capture phase. Browser). 15.8.4 Bubbling and Capturing When we discussed events in Chapter 13 we introduced capturing and bubbling to describe the flow of events in a program. The way that the events are captured differs in different browsers. In Mozilla Firefox, for example, the event comes to life at the window level and is sent down the tree of nodes until it finally reaches the target object for which it was intended, whereas with Internet Explorer the event springs to life for the target it was intended to affect, and then sends information about the event bubbling back up the chain of nodes. Handling the way events propagate has been another browser compatibility issue. The W3C DOM Level 2 allows the DOM nodes to handle events with a combination of these methods, but defaults to the bubble up propagation model. Figure 15.33 Event capturing and bubbling. Capturing Bubbling <a> <body> <p> <div> <a> <body> <p> <div> From the Library of WoweBook.Com ptg 15.8 Event Handling and the DOM 663 How Bubbling Works. In Figure 15.33, the document contains a <body> that con- tains a <div> that contains a <p> that contains an <a> tag. Now assume that a click event handler has been assigned to all four of them. When a user clicks the link, the events bubble up. The click’s original target, the <a>, gets to see the event first, and then passes it upward to the <p> for further processing, which passes it on to the <div>, which finally passes it up to the body of the document. This program was executed in three browsers, Firefox, Opera, and Internet Explorer. All of them use bubbling How Capturing Works. With capturing, when the user clicks the link, the link doesn’t get the event first. Instead, the event listener attached to the document grabs the event first and processes it. (That is, it captures the event before it gets to its intended target.) The event is then passed down to the <div>’s event handler. The event then goes to the <p>, and finally to the <a>. That is, all of the clicked-on object’s “ancestors” higher up in the document capture the event for processing before sending it down the chain to its intended target. See event listeners for setting event capturing. EXAMPLE 15.18 <html> <title>Bubbling</title><head> <script type="text/javascript"> /* This program behaves the same way in both Firefox and Internet Explorer and Opera. The W3C states bubbling as the default. */ 1 var d1,p1,p2,a1; 2 window.onload=function(){ 3 b1=document.getElementById('bdy1'); d1=document.getElementById('div1'); p1=document.getElementById('para1'); p2=document.getElementById('para2'); a1=document.getElementById('link1'); 4 b1.onclick=iam; d1.onclick=iam; p1.onclick=iam; p2.onclick=iam; a1.onclick=iam; } 5 function iam(){ alert(this.id); } </script> </head> 6 <body id="bdy1"> <h2>Bubble bubble </h2> <div id="div1"> Continues From the Library of WoweBook.Com ptg 664 Chapter 15 • The W3C DOM and JavaScript <p id="para1">Some text in a paragraph element.</p> <p id="para2">Another paragraph element with text. 7 <a id="link1" href="#">link</a> </p> </div> </body> </html> EXPLANATION 1 Global variables are declared for the script. 2 Once the page has loaded, the onload event is triggered and the anonymous func- tion is called. 3 The getElementById() method is used to get a reference to on the elements in the page: the body, the div, the paragraph, and the link. 4 For each element an onclick event is registered. The iam() function will be called when the event happens. When the user clicks the link, the function will be called and then bubble up to the parent of the link, its grandparent, and so on. If you start at say “para1” and click on that paragraph, the bubbling starts from there and ignores those events for “para2” and “link1”. 5 This function will be called when the click event happens on each of the elements listed above. See the output to see when this function is called. 6 The body of the page is given a unique id. 7 In this example, the user clicked the link, which started a chain of events bubbling up from there, as shown in Figures 15.34 and 15.35. Figure 15.34 The page before any event occurs. EXAMPLE 15.18 (CONTINUED) From the Library of WoweBook.Com ptg 15.8 Event Handling and the DOM 665 Stopping or Cancelling the Event Flow. The W3C event model allows you to cancel or stop the flow of a set of events from happening. In the last example, once you clicked on the link, the next click event happened, and so on, until the last element, the body, was reached. In the next example, the bubbling is stopped with the stopPropaga- tion() event method, a method provided to stop bubbling in W3C compliant browsers. Some event methods are given in Table 15.7. The cancelBubble Property (Internet Explorer). If using Internet Explorer, this is how you would cancel the bubbling in Example 15.19 with the cancelBubble property. If set to true this property disables bubbling for this event, preventing the next event in the hierarchy from receiving the event. event.cancelBubble = true; Figure 15.35 The user clicked on the link first, and it bubbled up from there for each element. The body element was last and at the top of the bubbling chain. Table 15.7 Event Methods stopPropagation() Prevent further propagation of an event during event flow. preventDefault() Cancels the event if it is cancelable, meaning that any default action normally taken when the event happens, will not occur. initEvent(eventType, isBubble, isCancelable) Event type such as click, mousedown, and so on. Boolean true or false to determine event’s default event flow, bubble or cancel. EXAMPLE 15.19 <html> <title>Bubbling Cancelled</title><head> <script type="text/javascript"> 1 var d1,p1,p2,a1; 2 window.onload=function(){ 3 b1=document.getElementById('bdy1'); Continues From the Library of WoweBook.Com ptg 666 Chapter 15 • The W3C DOM and JavaScript d1=document.getElementById('div1'); p1=document.getElementById('para1'); p2=document.getElementById('para2'); a1=document.getElementById('link1'); 4 b1.onclick=iam; d1.onclick=iam; p1.onclick=iam; p2.onclick=iam; a1.onclick=iam; } 5 function iam(event){ if (!e){ e = window.event; 6 e.cancelBubble = true;/* Microsoft IE*/ } else{ 7 e.stopPropagation(); /* W3C */ } // stop all other targets with event listeners from // triggering this event } </script> </head> 8 <body id="bdy1"> <h2>Bubble bubble </h2> <div id="div1"> 9 <p id="para1">Some text in a paragraph element.</p> <p id="para2">Another paragraph element with text. 10 <a id="link1" href="#">link</a> </p> </div> </body> </html> EXPLANATION 1 Global variables are declared that will be used in the function that follows. 2 Once the page has loaded the onload event handler is triggered, causing the anon- ymous function to be executed. 3 The document.getElementById() method returns references to all of the HTML el- ements with id attributes. 4 Each of the element references is assigned the onclick event property and its value, a function called iam(). EXAMPLE 15.19 (CONTINUED) From the Library of WoweBook.Com ptg 15.8 Event Handling and the DOM 667 5 When the click event is triggered, the function called iam() is sent to the event object and is received as a parameter. It contains data about the event, in this case the click event and the object that was clicked. (See Chapter 13.) 6 The cancelBubble property (Internet Explorer) returns or sets a Boolean that rep- resents whether the current event should bubble up the hierarchy of event han- dlers. If set to true, event bubbling is canceled, preventing the next event handler in the hierarchy from receiving the event. 7 The stopPropagation() method is used to prevent further propagation of an event during event flow. If this method is called by any event listener or handler, the event will stop bubbling up the DOM tree. The event will complete dispatch to all listen- ers on the current EventTarget before event flow stops. This method may be used during any stage of event flow so if you click the link, the bubbling will stop there or if you click on the div element, it will stop at that point and go no further. See http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-flow-cancelation. 8 An id attribute is assigned to the body element. 9 Two paragraphs within the div container are also given ids. 10 Within the second paragraph, an id is assigned to the <a> tag. If bubbling starts at the link, it will propagate upward through its ancestor tree to the all of those ele- ments that are waiting for a click event to happen, but in this example the bub- bling will stop right away because it is being canceled when the iam() function is called. See the results in Figures 15.36 and 15.37. Figure 15.36 The initial page before clicking on the link. EXPLANATION ( CONTINUED) From the Library of WoweBook.Com ptg 668 Chapter 15 • The W3C DOM and JavaScript 15.9 Event Listeners with the W3C Model 15.9.1 Adding an Event The addEventListener Method. The W3C event model adds the addEventLis- tener() method, which registers a single event listener on a document, a window, a DOM node or X(HTML), or an Ajax XMLHttpRequest (see Chapter 18, “An Introduction to Ajax (with JSON)”). This method takes three arguments: 1. The event type to listen for (mouseover, click, etc.). 2. A function to be executed when the event is fired. 3. A Boolean (called useCapture) of true or false to specify the event propagation type: true to turn on event capturing and false to turn on event bubbling (the most cross-browser-compliant way is false). Figure 15.37 Further bubbling stops after a user clicks the link. FORMAT target.addEventListener(type, listener, useCapture); EXAMPLE var div1 = document.getElementById("mydiv"); div1.addEventListener('click',sayWelcome,false); From the Library of WoweBook.Com . the layers; that is, the separation of markup from JavaScript. 15.8.2 The Scripting Way To keep the markup and the JavaScript separate, the JavaScript provided a way for pro- grammers to apply. print news across the image. From the Library of WoweBook.Com ptg 662 Chapter 15 • The W3C DOM and JavaScript window.onload=function(){ document.getElementById("bdy").style.backgroundColor="lightgreen"; } 15.8.3. 15.18 <html> <title>Bubbling</title><head> <script type="text /javascript& quot;> /* This program behaves the same way in both Firefox and Internet Explorer