ptg 13.8 The Scripting Model for Handling Events 517 13.8 The Scripting Model for Handling Events We have been using event handlers like onClick, onSubmit, and onMouseOver, through- out this text. So far, this chapter has described in detail all of the different event handlers and how to use them as inline HTML attributes. Inline event handling is the oldest and simplest way to handle events and is browser compatible. The following example uses the onClick handler as an attribute of the button element. When the user clicks the but- ton, 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/presentation from behavior/ JavaScript. To solve this prob- lem, we can handle events within the JavaScript code itself. All of the HTML attributes used as event handlers can also be used as DOM properties. These properties can be used in JavaScript to simulate the event that they are named for. If, for example, you want to trigger a window event, JavaScript views the window as an object and any event associ- ated with it as a property. If you want to use the onload event with the window object, you would say window.onload. The main difference is that unlike using HTML attributes, which take a string value, a function reference is assigned to an event handler. All Java- Script event properties must be in lowercase, such as window.onload or window.ununload. (The event handlers, used as HTML attributes, are not case sensitive, so ONUNLOAD, onUnLoad, and onunload are all acceptable.) Here’s an example: window.unload=some_function; 13.8.1 Getting a Reference to the Object To assign an event property to an object, JavaScript will need a reference to the object. For example, if the click event is to be triggered when the user clicks a button, then Java- Script will need to use a reference to the button. By assigning an id to the HTML button, JavaScript can use the DOM’s getElementById() method to get the reference it needs. In the HTML part of the document: input type button id=”button1”> In the JavaScript script: var b1=document.getElementById("button1"); Now b1 in the script is a reference to “button1” from the HTML document. After JavaScript has a reference to the HTML element, the name of the event, such as click or onmouseover can be used as a property: b1.click b1.mouseover From the Library of WoweBook.Com ptg 518 Chapter 13 • Handling Events The next step is to assign a value to the event property. The value will be a reference to either a named function or an anonymous function. Note: When used as a reference, the function name is not enclosed in quotes and does not have parentheses! b1.click=greetings; function greetings(){ alert("Welcome!"); } or an anonymous function b1.click=function(){alert(“Welcome!”);} Now when the user clicks “button1” in the document, the JavaScript event handler will be triggered and the greeting displayed in an alert box. Another example of using JavaScript event handling is with the onload event. This event is used to guarantee that the entire page has been loaded before an event is fired. When a function is assigned to onload, the function will not be executed until the page has loaded: window.onload = init; function init() { do_something } You can also assign an anonymous function to the onload property as follows: window.onload = function(){ do something; } See Example 13.26. When the page has loaded, the function that was registered to the event will be called. If you want to assign more than one function to the event, there are several ways to do this. One method is to place several function calls in a chain, using one onload event handler. function start() { func1(); func2(); } window.onload = start; Like the inline model, each event can only have one event handler registered. To remove an event handler, simply set the property to null. Object event properties are shown in Table 13.11. For a more elegant examples of how to use onload go to http://www.site- point.com/blogs/2004/05/26/closures-and-executing-JavaScript-on-page-load/. From the Library of WoweBook.Com ptg 13.8 The Scripting Model for Handling Events 519 Table 13.11 Object Event Properties Event Handler Property Event onblur blur onfocus focus onchange change onmouseover mouseover onmousemove mousemove onmousedown mousedown onmouseup mouseup onclick click ondblclick dblclick onkeydown keydown onkeyup keyup onkeypress keypress onsubmit submit onload load onunload unload EXAMPLE 13.26 <html> <head><title>Event Handling and Forms</title> <script type="text/javascript"> 1 var b1,b2,b3; 2 window.onload=function(){ 3 b1=document.getElementById("button1"); b2=document.getElementById("button2"); b3=document.getElementById("button3"); 4 b1.onclick=morning; b2.onclick=noon; b3.onclick=night; } Continues From the Library of WoweBook.Com ptg 520 Chapter 13 • Handling Events 5 function morning(){ alert ("Good Morning"); } function noon(){ alert("Let's have lunch."); } function night(){ alert("Good-night!"); } </script> </head> <body> <h2> Greetings Message </h2> <hr /> <form> 6 <input type="button" id="button1" value="Morning" /> <input type="button" id="button2" value="Noon" /> <input type="button" id="button3" value="Night" /> </form> </body> </html> EXPLANATION 1 Some global variables are defined to be used later in the script. 2 The onload event property of the window object mimics the behavior of the HTML onLoad event handler of the body element. The function defined will be called when a document or frameset is completely loaded into its window or frame. 3 The document.getElementById() method takes the id of each of the HTML buttons and returns a reference to each of them. Now JavaScript has access to the buttons. 4 Using the onclick property with the button reference allows JavaScript to react to the click event when the user clicks one of the buttons. The function called morn- ing is assigned to this property and will be called when “button1” is clicked. Note that this is a reference to the function and there are no quotes or parentheses. The actual function it references is on line 5. 5 This is the actual function that will be called when the user clicks the “Morning” button. 6 Three HTML buttons are defined in the document. Each is given a unique id to be used in the JavaScript program as an argument to the document.getElementById() method. See Figures 13.44 and 13.45. EXAMPLE 13.26 (CONTINUED) From the Library of WoweBook.Com ptg 13.8 The Scripting Model for Handling Events 521 In Example 13.27, an image is assigned to the HTML <a> tag. When the user rolls the mouse over the initial image, the image is replaced with a new image. Rather than have the onMouseOver and onMouseOut event handlers used as attributes to the HTML link tag, they will be properties to the link object in the JavaScript code. This allows the pro- gram to separate the structure (HTML) from the behavior (JavaScript). Figure 13.44 The HTML page before clicking one of three buttons. Figure 13.45 The user clicked the first button. From the Library of WoweBook.Com ptg 522 Chapter 13 • Handling Events EXAMPLE 13.27 <html> <head><title>Preloading Images</title> <script type="text/javascript"> 1 window.onload=preLoad; 2 function preLoad(){ 3 var linkId=document.getElementById("link1"); baby = new Array(); // global variable baby[0]=new Image(); // Preload an image baby[0].src="babysmile.jpg"; baby[1]=new Image(); baby[1].src="babygoo.jpg"; 4 linkId.onmouseover=firstBaby; // Event property on a link 5 linkId.onmouseout=secondBaby; } 6 function firstBaby(){ document.images["willy"].src=baby[1].src; } 7 function secondBaby(){ document.images["willy"].src=baby[0].src; } </script> </head> <body> <h1>This is Baby William</h1> 8 <a id="link1"><img name="willy" src="babygoo.jpg" width="220" height="250"> </a> </body> </html> EXPLANATION 1 The onload property of the window object simulates the HTML onLoad event han- dler of the body element. The function preLoad() will be called when a document or frameset is completely loaded into its window or frame. 2 This function will be called as soon as the document has loaded. It will preload the images and set up the event handling. 3 To apply a property to a link, we need to get a reference. The getElementById() method returns a reference, linkID, to the link object identified on line 8 with a unique id. 4 The mouseover event handler property is assigned to linkId. Its value is a reference to a function, called firstBaby(), and defined on line 6. The function will be called when the mouseover event happens. 5 The mouseout event is a property of linkId. When the mouseout event happens the function secondBaby() will be called. From the Library of WoweBook.Com ptg 13.9 What You Should Know 523 13.9 What You Should Know The day the music died the day events died, is when JavaScript ceased to exist. It would be a challenge to find a JavaScript program that doesn’t have an event handler. Events are the basis for interactivity and without them, a Web page is dead. This chapter focused on all the major event handlers you can use in JavaScript, what triggers them, and how to register them. We saw that event handlers can be assigned to objects such as buttons, links, windows, and forms and that when a user rolls the mouse over an object, clicks a button, presses a key, resizes the window, submits a form, or changes a value, JavaScript can react and do something based on those actions. The simplest way to use the handlers is as attributes of HTML tags, but in doing so, JavaScript is made part of the HTML markup. To keep the structure (markup) and the behavior (JavaScript) separate, the event handlers can be used as properties of objects. In Chapter 15, we will take this to the next level, working with event handlers and the DOM. So far, you should know: 1. How to create an inline event handler. 2. What it means to register an event. 3. When the return value from the event handling function is necessary. 4. How to use JavaScript event methods. 5. How the onblur and onfocus event handlers are used. 6. What event handlers are used with windows and frames. 6, 7 These are the functions that are called when the mouse events are triggered. 8 The HTML <a> tag is given an id of “link1” and assigned an initial image. The out- put is shown in Figure 13.46. Figure 13.46 Mouse rolls over first baby. Image is replaced with second baby. EXPLANATION ( CONTINUED) From the Library of WoweBook.Com ptg 524 Chapter 13 • Handling Events 7. How to use mouse events. 8. How mouse events are used with a rollover. 9. What event handlers are used with links. 10. How a button input device differs from a submit input device. 11. What events are used with forms. 12. How to prevent a form’s submission. 13. What the event object is. 14. The difference between capturing and bubbling. 15. How you can tell what element fired the event: Internet Explorer? Firefox? 16. How to pass an event to a JavaScript function. 17. How to get the coordinate positions of a mouse within an element. 18. How to handle key events. 19. How to use the scripting model for handling events. From the Library of WoweBook.Com ptg 13.9 What You Should Know 525 1. Create three buttons, labeled Shoot movies, Shoot guns, and Shoot basketballs. When the user clicks any button, use the onClick event handler to call a func- tion that will send a message based on which button was pressed. 2. Create a form that contains two text fields to receive the user’s name and address. When the user leaves each text field, use the onBlur event handler to check if the user entered anything in the respective field. If the user didn’t, send an alert telling him or her so, and use the focus() method to return focus back to the text field the user just left. 3. Make a link that changes the background color to light blue when the mouse pointer is rolled over it. 4. Create a form that will contain a textbox. After the user enters text, all the let- ters will be converted to lowercase as soon as he or she clicks anywhere else in the form. (Use the onChange event handler.) 5. Write a script that will detect what event occurred and the pixel positions of a mouse when it rolls over a hotspot in an image map. 6. Create a text field in a form. When the user clicks on a button, a function will be called to make sure the field is not empty. In a JavaScript program use the document.getElementByIdI() method to get a reference to the button object. Use the onclick event property. 7. Write the HTML part of this script to test capturing and bubbling for your browser. Explain the order of event handling. document.onclick = function(){ alert("Document clicked!"); }; function buttonClick(){ alert("Button clicked!"); } function formClick(){ alert("Form clicked!"); } 8. Rewrite Example 13.5 using the scripting method. The onload event handler will be used as a property of the window object. The definition of the now() function will be the value assigned to the event handler; it will be anonymous. Exercises Exercises From the Library of WoweBook.Com ptg 526 Chapter 13 • Handling Events The onunload event handler will also be made part of the JavaScript code. After you have tested your program, put the JavaScript program in an external .js file. In the HTML file, use the src attribute of the script tag to include the .js file and run your program. All JavaScript is now separated from the HTML markup. From the Library of WoweBook.Com . the HTML button, JavaScript can use the DOM’s getElementById() method to get the reference it needs. In the HTML part of the document: input type button id=”button1”> In the JavaScript script: var. changes a value, JavaScript can react and do something based on those actions. The simplest way to use the handlers is as attributes of HTML tags, but in doing so, JavaScript is made part of the. Handling Events The onunload event handler will also be made part of the JavaScript code. After you have tested your program, put the JavaScript program in an external .js file. In the HTML file,