As explained in Chapter 13, interactive JavaScript programs use an event-driven programming model. In this style of programming, the web browser generates an event whenever something interesting happens to the document or to some element of it. For example, the web browser generates an event when it finishes loading a document, when the user moves the mouse over a hyperlink, or when the user clicks on a button in a form. If a JavaScript application cares about a particular type of event for a particular document element, it can register an event handlera JavaScript function or snippet of codefor that type of event on the element of interest. Then, when that particular event occurs, the browser invokes the handler code. All applications with graphical user interfaces are designed this way: they sit around waiting for the user to do something interesting (i.e., they wait for events to occur), and then they respond. As an aside, it is worth noting that timers and error handlers (both of which are described in Chapter 14) are related to the event-driven programming model. Like the event handlers described in this chapter, timers and error handlers work by registering a function with the browser and allowing the browser to call that function when the appropriate event occurs. In these cases, however, the event of interest is the passage of a specified amount of time or the occurrence of a JavaScript error. Although timers and error handlers are not discussed in this chapter, it is useful to think of them as related to event handling, and I encourage you to reread Sections 14.1 and 14.7 in the context of this chapter. Most nontrivial JavaScript programs rely heavily on event handlers. Past chapters have included a number of JavaScript examples that use simple event handlers. This chapter fills in all the missing details about events and event handling. Unfortunately, these details are more complex than they ought to be because three distinct and incompatible event-handling models are in use.[*] These models are:
This chapter documents each of these event models in turn. Coverage of the three event models is followed by three sections that include extended examples of handling mouse, keyboard, and onload events. The chapter concludes with a brief discussion of creating and dispatching synthetic events. |