Chapter 17. Events and Event Handling

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 handler—a JavaScript function or snippet of code—for 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 ...

Get JavaScript: The Definitive Guide, 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.